I'm trying to send a nested PHP array to Javascript. But Javascript parses the top level as an object.
The Teams array should contain 2 other arrays with each 2 team names
As you can see in the screenshot and the json, the "Teams" is an object.
"teams":{"1":["test","test"],"2":["test","test"]},"results":[]}
This is the code I'm using to build up the nested array
$iterator = 0;
for($i = 0; $i < $competition->teams->count(); $i++) {
if($i % 2 == 0) {
$iterator++;
}
$data["teams"][$iterator][] = "test";
}
The funny thing is, it is working when the array is not multidimensional. For example the following example doesn't return Teams as an object.
I'm guessing if I remove the array keys it might work, but It's impossible to have a nested array without array keys, right?
Thank you!
There is one problem with your code, $iterator
always starts with value 1
so json_encode
function uses JSON object to preserve that index.
Everything changes when you start indexing your array from 0
instead.
$test = array(
1 => 'test'
);
echo json_encode($test);
Shows {"1":"test"}
which is an object.
$test = array(
0 => 'test'
);
echo json_encode($test);
Shows ["test"]
which is an array.