json_encode Encodes Sparse Arrays as JSON Objects
When JSON-encoding sparse arrays (i.e., arrays with missing indices), PHP's json_encode function exhibits unexpected behavior, converting the array into a JSON object instead of an array. To understand this behavior, let's examine an example:
$a = array( new stdClass, new stdClass, new stdClass ); $a[0]->abc = '123'; $a[1]->jkl = '234'; $a[2]->nmo = '567'; printf("%s\n", json_encode($a)); unset($a[1]); printf("%s\n", json_encode($a));
Output:
[{ "abc": "123" },{ "jkl": "234" },{ "nmo": "567" }] { "0": { "abc": "123" }, "2": { "nmo": "567" } }
In the initial encoding, json_encode produces an array of objects since the sparse array is valid as an object. However, after removing an index (1) with unset, the resulting array cannot be encoded as an array because it now has a hole.
To resolve this issue and ensure the array remains encoded as an array, use array_values($a) before encoding:
printf("%s\n", json_encode(array_values($a)));
[{ "abc": "123" },{ "nmo": "567" }]
By reindexing the array with array_values, any gaps are removed, allowing json_encode to successfully produce a valid JSON array.
The above is the detailed content of Why Does PHP\'s `json_encode` Convert Sparse Arrays to JSON Objects?. For more information, please follow other related articles on the PHP Chinese website!