Sparse Arrays Encoded as JSON Objects in json_encode
When an array contains a missing index, it's known as a sparse array. json_encode, by default, handles sparse arrays as JSON objects instead of arrays. This can lead to unexpected behavior in various scenarios.
Cause of Array-to-Object Conversion
JSON syntax doesn't support arrays with missing indices. When json_encode encounters a sparse array, it assumes it's an object and converts it accordingly.
Example
Consider the following code:
$a = array( new stdClass, new stdClass, new stdClass ); $a[0]->abc = '123'; $a[1]->jkl = '234'; $a[2]->nmo = '567'; // First JSON encoding echo json_encode($a) . "\n"; // Unset an element unset($a[1]); // Second JSON encoding echo json_encode($a) . "\n";
Output
[{"abc":"123"},{"jkl":"234"},{"nmo":"567"}] {"0":{"abc":"123"},"2":{"nmo":"567"}}
In the first encoding, the array is converted to a JSON array as expected. However, after unsetting index 1, the second encoding results in a JSON object due to the sparse array issue.
Prevention
To prevent this behavior and ensure consistent array encoding, you can use array_values() to reindex the array before passing it to json_encode. This will remove any holes in the array and ensure it's treated as an array by json_encode.
Modified Code
echo json_encode(array_values($a)) . "\n";
This modified code will always encode $a as a JSON array, regardless of whether it has missing indices or not.
The above is the detailed content of Why Does `json_encode` Convert Sparse PHP Arrays to JSON Objects?. For more information, please follow other related articles on the PHP Chinese website!