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.
2 Answers 2
UPDATE:
To rephrase the problem:
desired is an array for which indices correspond to IDs of given objects. For every missing ID, the array item at that index must be
null.
from the provided example, it can be seen that IDs of objects in $data are zero indexed, so we initialize and array with a length of max(ID) + 1 and fill it as you did previously. However and IMHO, I think this would be a misuse of array data structure. If you have huge gaps in your IDs, your array would contain a big number of nulls. Since JS doesn't have associative arrays, the best option would be to convert your array into an object (as PHP did in your case).
Since $data is not given, this is the best what I came up with:
generally json_encode returns an object if you have an associative array, otherwise, you'll get a normal JSON array. So you might wanna try something like this:
echo json_encode( array_values($return) );
5 Comments
max(ID) + 1 as array length.If your IDs aren't sequential, then count($data) is not going to give the results you are looking for. For example, if $data has keys 1, 2, 3, and 5; then array_fill will only give you keys 0-3 on $return, and you'll end up with a non-sequential array.
Try this instead:
$return = [];
$length = max(array_keys($data));
$return = array_fill(0, $length, null);
$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.