图表。js数据数组使用PHP, MySQL。如何从JSON数组定义数据源?

时间:2022-10-22 20:46:39

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. The graph I intend to draw is a simple vertical barchart, birth_year vs number of people born. When I display the arrays $BIRTH_YEAR and $COUNTS, I could see the values. I was able to get to the point till json_encode($data_array). When I try to use this encoded array on javascript, I do not get any output, a blank page! Here is my code.

我正在试着用图表画一张图表。带有PHP和MySQL数据的js。我要画的图表是一个简单的垂直条形图,出生年份与出生人数之比。当我显示数组$BIRTH_YEAR和$COUNTS时,我可以看到这些值。直到json_encode($data_array)为止,我都能做到这一点。当我尝试在javascript上使用这个编码数组时,我不会得到任何输出,一个空白页!这是我的代码。

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. When I use the chart.js sample file I was able to see charts. The only issue is I am not sure how to include arrays in javascript data: part. Thanks in advance.

我已经在我的页面中包含了所有其他必需的HTML元素。当我使用图表的时候。js样本文件我可以看到图表。唯一的问题是我不确定如何在javascript数据:part中包含数组。提前谢谢。

1 个解决方案

#1


2  

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); ?>

#1


2  

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); ?>