[Chartjs]-Passing JSON data from PHP array into ChartJS

2👍

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>

Leave a comment