I am creating a multidimensional array via an Ajax call to populate a Google Chart (Column). However the Array that is getting returned is causing this error:
Uncaught Error: Not a valid 2D array.
This is the code that generates the array to send back:
$chartData = array();
$i = 0;
foreach ($hourVal as $value) {
if($i <= 9){
$chartData[] = array(
"0" . $i => (int) $value
);
} else {
$chartData[] = array(
$i => (int) $value
);
}
$i++;
}
This is the array when I console.log:
[
[
"Terms",
"Visits"
],
{
00: 88
},
{
01: 30
},
{
02: 44
},
{
03: 20
}
]
EDIT: I add a row at the beginning of the array and also json_encode:
array_unshift($chartData, array("Terms","Visits"));
echo json_encode($chartData);
Any ideas what is going on and how I can fix this?
That's not a 2D array. it's an array of objects (and one array). When you do json_encode
, you only get an array if your PHP array is a numeric one (indexed starting at 0
). Otherwise you get an object (since JavaScript/JSON doesn't have "associative arrays").
You need to make sure your array is numeric and indexed starting from 0
.
$chartData = array();
$i = 0;
foreach ($hourVal as $value) {
$chartData[] = array(
$i => (int) $value
);
$i++;
}
I don't know why you were doing "0" . $i
"0" . $i
, but that's what was causing your problem. That was creating an "associative array", which encodes as an object.
I have solved it, its because I was sending them through with a prefix of 0 and then it was making them the index of the array. Had to cut that bit out and send as string. Not desired but a fix :(
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.