Understanding JSON Encoding of Sparse Arrays
In JSON encoding, sparse arrays (arrays with missing index values) are an anomaly. This is because JSON's array syntax does not support indices, making it impossible to represent such arrays directly.
Question:
Why does json_encode encode a sparse array as a JSON object instead of an array?
Answer:
The behavior of json_encode with sparse arrays stems from the inability of JSON to express such arrays. When json_encode encounters a sparse array, it resorts to encoding it as a JSON object to maintain the key-value pairs of the array.
Example:
Consider the PHP code:
$a = array( new stdclass, new stdclass, new stdclass ); $a[0]->abc = '123'; $a[1]->jkl = '234'; $a[2]->nmo = '567'; echo json_encode($a) . "\n"; unset($a[1]); echo json_encode($a) . "\n";
Output:
[{"abc":"123"},{"jkl":"234"},{"nmo":"567"}] {"0":{"abc":"123"},"2":{"nmo":"567"}}
Explanation:
Solution:
To prevent the encoding of a sparse array as an object, you can use array_values($a) to obtain a reindexed array without any holes. json_encode will then properly encode this as a JSON array.
The above is the detailed content of Why Does `json_encode` Convert Sparse Arrays to JSON Objects?. For more information, please follow other related articles on the PHP Chinese website!