将JSON数据从PHP数组传递到ChartJS

时间:2015-03-04 14:28:37

标签: javascript php json wordpress chart.js

所以我有一个PHP数组是根据从WordPress中的高级自定义字段中提取的数据创建的:

<?php
  $chartArray = array();
  forEach($cat_meta as $key => $value) {
  $chartArray[] = array($value['star_rating']);
  }
  echo json_encode($chartArray);
?>

这将在页面上输出以下内容:

[[&#34; 2&#34;],[&#34; 4&#34;],[&#34; 1&#34;],[&#34; 3&#34;],[& #34; 5&#34;]]

我想要做的是将结果输入ChartJS文件的数据变量:

var radarChartData = {
labels: ["Price", "Speed", "Format", "Size", "User Experience"],
datasets: [
    {
        label: "My First dataset",
        fillColor: "rgba(220,220,220,0.2)",
        strokeColor: "rgba(224,07,19,1)",
        pointColor: "rgba(224,07,19,1)",
        pointStrokeColor: "#fff",
        pointHighlightFill: "#fff",
        pointHighlightStroke: "rgba(224,07,19,1)",
        data: [5, 4, 5, 5, 1, 3] // data needs to replace this
    }
]
};

var ctx = document.getElementById('RadarChart').getContext('2d');
var myRadarChart = new Chart(ctx).Radar(radarChartData);

我有点像PHP / Javascript n00b,所以我希望有人能够为我阐明这一点。或者也许有更好的方法来做到这一点?提前谢谢。

1 个答案:

答案 0 :(得分:2)

将数组中的JS对象/数据作为字符串存储在PHP中并打印出来。

<?php

// start script
$str = '<script>';
// start chart
$str .= 'var radarChartData = {';
// make labels
$str .= 'labels: [';
$delimiter = '';
foreach($chartArray as $key => $val){
    $str .= $delimiter.'"'.$key.'"';
    $delimiter = ', ';
}
// make dataset
$str .= '], datasets: [{';
$str .= 'label: "My First dataset", ';
$str .= 'fillColor: "rgba(220,220,220,0.2)", ';
$str .= 'strokeColor: "rgba(224,07,19,1)", ';
$str .= 'pointColor: "rgba(224,07,19,1)", ';
$str .= 'pointStrokeColor: "#fff", ';
$str .= 'pointHighlightFill: "#fff", ';
$str .= 'pointHighlightStroke: "rgba(224,07,19,1)",';
$str .= 'data: [';
$delimiter = '';
foreach($chartArray as $key => $val){
    $str .= $delimiter.$val;
    $delimiter = ', ';
}
$str .= ']}]};';
// end script
$str .= "</script>";
// print
print $str;

?>

<canvas id='RadarChart' class='chart' width='400px' height='400px'></canvas>

<script>
var ctx = document.getElementById('RadarChart').getContext('2d');
var polar_big5 = new Chart(ctx).Radar(radarChartData);
</script>