doy51723 2015-03-04 14:28
浏览 88

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

So I have a PHP array created from data pulled from Advanced Custom Fields in WordPress:

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

This outputs the following on the page:

[["2"],["4"],["1"],["3"],["5"]]

What I'm trying to do is get that result into the data variable of the ChartJS file:

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

I am a bit of a PHP / Javascript n00b so I'm hoping someone might be able to shed some light on this for me. Or maybe there is a better way of doing this? Thank you in advance.

  • 写回答

1条回答 默认 最新

  • doufanglian7585 2015-03-27 12:51
    关注

    Store the JS object/data from the array as a string in PHP and print it.

    <?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>
    
    评论

报告相同问题?