如何将值传递给图表 (chart.js / morris.js)

How to pass values to a chart (chart.js / morris.js)

使用 PHP 我试图从 MySQ 数据库获取数据并将其显示在面积图(收入)上。 以下是我的 PHP 代码:

$q = "SELECT `sales`, `quantity` FROM `sap` WHERE `d_channel`='$disC' AND `sales_org`='$plant' AND `date` BETWEEN '$fd' AND '$td'";
$result = mysqli_query($dbc,$q);

$array = array();
while($row = mysqli_fetch_assoc($result))
{
    array_push(
        $array,
        array(
            'x' => $row['sales'],
            'y' => $row['quantity'],
        )
    );                
}

echo json_encode($array);

和输出 是:

[
  {"x":"101151.7","y":"10"},
  {"x":"14660.53","y":"20"},
  {"x":"505344","y":"50"}
]

我已经将数组传递给图表如下:

<div id="morris-line-chart"></div>

<script>
    Morris.Line({
        // ID of the element in which to draw the chart.
        element: 'morris-line-chart',

        // Chart data records -- each entry in this array corresponds to a point
        // on the chart.
        data: <?php echo json_encode($array);?>,

        // The name of the data record attribute that contains x-values.
        xkey: 'cron_time',

        // A list of names of data record attributes that contain y-values.
        ykeys: ['images_processed'],

        // Labels for the ykeys -- will be displayed when you hover over the
        // chart.
        labels: ['Images Processed'],

        lineColors: ['#0b62a4'],
        xLabels: 'hour',

        // Disables line smoothing
        smooth: true,
        resize: true
    });
</script>

但是报错"Uncaught TypeError: Cannot read property 'match' of undefined" 供参考 我使用了以下链接

<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.min.js"></script>

请帮我解决问题。

尝试改变你的xkeyykeys。因为您的实际 cron_timeimages_processed 不存在于您的 json 数据中。

xkey: 'x', // 'cron_time',
ykeys: ['y'], //['images_processed'],

或者更改 php 中的键并保留实际的 Morris 配置:

array
(
    'cron_time' => $row['sales'],
    'images_processed' => $row['quantity'],
)

您还应该将 quantity 转换为 intfloat:

(int)$row['quantity']
(float)$row['quantity']