简体   繁体   English

使用PHP,MySQL的Chart.js数据数组。 如何从JSON数组定义数据源?

[英]Chart.js data array using PHP, MySQL. How to define datasource from JSON array?

This is my first question. 这是我的第一个问题。 Kindly apologize for any errors. 如有任何错误,敬请原谅。

I am trying to draw a chart using chart.js with PHP and MySQL data. 我正在尝试使用带有PHP和MySQL数据的chart.js绘制图表。 The graph I intend to draw is a simple vertical barchart, birth_year vs number of people born. 我打算绘制的图形是一个简单的垂直条形图,birth_year与出生人数。 When I display the arrays $BIRTH_YEAR and $COUNTS, I could see the values. 当显示数组$ BIRTH_YEAR和$ COUNTS时,可以看到这些值。 I was able to get to the point till json_encode($data_array). 我直到json_encode($ data_array)为止。 When I try to use this encoded array on javascript, I do not get any output, a blank page! 当我尝试在javascript上使用此编码数组时,没有任何输出,空白页! Here is my code. 这是我的代码。

while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$data[] = array(
    $row['BIRTH_YEAR']=>$row['counts'],
);
$BIRTH_YEAR[]=$row['BIRTH_YEAR'];
$COUNTS[]=$row['counts'];
}

// JSON arrays for labels and counts
$js_labels = json_encode($BIRTH_YEAR,true);
$js_cols = json_encode($COUNTS,true);


var barChartData = {
        labels : '<?php echo $js_labels; ?>',
                    datasets : [
            {
                fillColor : "rgba(220,220,220,0.5)",
                strokeColor : "rgba(220,220,220,1)",
                data : '<?php echo $js_cols; ?>'
            }

        ]
                   }

var myLine = new Chart(document.getElementById("canvas").getContext("2d")).Bar(barChartData);

I have included all other required HTML elements in my page. 我在页面中包含了所有其他必需的HTML元素。 When I use the chart.js sample file I was able to see charts. 当我使用chart.js示例文件时,我能够看到图表。 The only issue is I am not sure how to include arrays in javascript data: part. 唯一的问题是我不确定如何在javascript数据中包含数组:部分。 Thanks in advance. 提前致谢。

You could use $js_cols = json_encode($COUNTS,JSON_NUMERIC_CHECK); 您可以使用$js_cols = json_encode($COUNTS,JSON_NUMERIC_CHECK);

and then 然后

data : <?php echo print_r($js_cols,true); ?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM