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

时间:2015-12-03 05:38:58

标签: javascript php json 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>

但它给出了一个错误&#34; Uncaught TypeError:无法读取属性&#39;匹配&#39;未定义&#34; FYI 我使用了以下链接

<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>

请帮我解决问题。

1 个答案:

答案 0 :(得分:1)

尝试更改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']