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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17984772/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 10:19:50  来源:igfitidea点击:

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

phpjavascriptmysqljson

提问by Nariman

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 数据的 chart.js 绘制图表。我打算绘制的图表是一个简单的垂直条形图,即birth_year 与出生人数的关系。当我显示数组 $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 元素。当我使用 chart.js 示例文件时,我能够看到图表。唯一的问题是我不确定如何在 javascript 数据中包含数组:部分。提前致谢。

采纳答案by Hernán Eche

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