0

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!

1
  • 3
    If you remove the json_encode() in 'data' => json_encode does that help, you should be encoding the whole array structure and not just one parts at a time. Commented Feb 15, 2021 at 15:57

1 Answer 1

3

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.