The question is published on by Tutorial Guruji team.
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!
Answer
You’re double-encoding some of the data. Look at this:
json_encode(array_values($val_ca_1), JSON_NUMERIC_CHECK)
That will pre-encode that part of the data as a string inside $dataSets
. So it’s already JSON. When you come to convert the whole of $dataSets
to JSON, it treats it as the simple string it’s already been converted to, rather than an array.
The solution is simple – don’t encode different parts of the data separartely. Keep it all in PHP variables and then turn all of it into a JSON string right at the last moment, when you actually need to.
In practical terms, in your code, just change
'data' => json_encode(array_values($val_ca_1), JSON_NUMERIC_CHECK)
to
'data' => array_values($val_ca_1)