I have an array in PHP which contains a list of objects:
// This is a var_dump of $data
array(3911) {
[0]=>
object(stdClass)#44 (3) {
["ID"]=>
string(1) "1"
["name"]=>
string(9) "Forest"
}
[1]=>
object(stdClass)#43 (3) {
["ID"]=>
string(1) "2"
["Name"]=>
string(3) "Lt. Dan"
}
// etc ...
}
I am converting that array into a flat index based array:
$return = [];
$length = count($data);
$return = array_fill(0, $length, null);
// Convert list into flat array
foreach ( $data as $item ){
$return[(int)$item->ID] = $item->name;
}
header( 'Content-Type: application/json' );
echo json_encode( $return );
The result I'm getting with json_encode is an object list:
{"0":null,"1":"Forest","2":"Lt. Dan","3":"Bubba","4":"Jenny"}
What I am expecting to get is:
[null,"Forest","Lt. Dan","Bubba","Jenny"]
How do I get json_encode to return a Javascript array instead of a Javascript object?
Side note: The Manual says that:
When encoding an array, if the keys are not a continuous numeric sequence starting from 0, all keys are encoded as strings, and specified explicitly for each key-value pair.
But my array is a continous set, that's why I am using array_fill.
$dataobject to this post, or at least the relevant parts of it?json_encodeexpects the array to be a sequential list and my ID's aren't always sequential.