I would like to convert a PHP array with json_encode to use values in javascript Chart.js
What I have is:
$dataSets = [ 0 => [
'type' => 'line',
'data' => json_encode(array_values($val_ca_1), JSON_NUMERIC_CHECK),
'backgroundColor' => 'transparent',
'borderColor' => '#007bff',
'pointBorderColor' => '#007bff',
'pointBackgroundColor' => '#007bff',
'fill' => false
],
];
With $val_ca_1 = array('2021-02-01' => 10, '2021-02-02' => 14, '2021-02-03' => 8);
What I do in javascript:
new Chart($visitorsChart, {
data: {
labels: ['2021-02-01', '2021-02-02', '2021-02-03'],
datasets: <?php echo json_encode($dataSets); ?>
},
options: {
maintainAspectRatio: false,
tooltips: {
mode: mode,
intersect: intersect
},
But it displays:
data: {
labels: ['2021-02-01', '2021-02-02', '2021-02-03'],
datasets: [{
"type": "line",
"data": "[10,14,8]"
"backgroundColor": "transparent",
"borderColor": "#007bff",
"pointBorderColor": "#007bff",
"pointBackgroundColor": "#007bff",
"fill": false
}]
},
And there is a problem with 'data', it has to be:
"data": [10,14,8]
(without double quotes) Any idea? Thanks!
json_encode()in'data' => json_encodedoes that help, you should be encoding the whole array structure and not just one parts at a time.