Reputation: 956
I am having so much confusion on this one. Highcharts has a specific format it accepts data in the series. It has to be like this for example:
[ { name: 'Title Here', data: [1,2,3,4,5] } ]
My issues though is, my ajax in php using json_encode() is converting the entire array of data I'm sending back to an js object like this:
$data = [
'name' => 'Percent',
'data' => [1,2,3,4]
];
return json_encode($data);
// Returned Result
{name: "Percent", data: {0: 1, 1: 2, 2: 3, 4: 4}}
This is causing issue with the chart in rendering the returned data. How would I convert the returned data to the first and correct way? I'm lost on how to complete this.
Upvotes: 0
Views: 722
Reputation: 340055
The format that Highcharts requires is a JavaScript Array
containing an Object
.
PHP's json_encode
function will encode a plain array as the former, but an associative array with string keys will automatically be encoded as the latter. You therefore just need to wrap your existing data in one more layer of array:
$data = [
[
'name' => 'Percent',
'data' => [1, 2, 3, 4]
]
];
I note however that you've said that the plain array [1, 2, 3, 4]
appears to have converted into the object {0:1, 1:2, 2:3, 3: 4}
.
This is not standard PHP json_encode
behaviour, and is perhaps a quirk of the Laravel Response::json([ ])
call you're really using?
Upvotes: 1
Reputation: 291
$data = [[
'name' => 'Percent',
'data' => [1,2,3,4]
]];
return json_encode($data);
In JavaScript has no native associative arrays, your array ['name'=>...]
translates to object when you apply json_encode()
to it.
Upvotes: 1