Home > Backend Development > PHP Tutorial > Why Does `json_encode` Convert Sparse Arrays to JSON Objects?

Why Does `json_encode` Convert Sparse Arrays to JSON Objects?

Susan Sarandon
Release: 2024-11-25 08:55:12
Original
830 people have browsed it

Why Does `json_encode` Convert Sparse Arrays to JSON Objects?

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";
Copy after login

Output:

[{"abc":"123"},{"jkl":"234"},{"nmo":"567"}]
{"0":{"abc":"123"},"2":{"nmo":"567"}}
Copy after login

Explanation:

  • In the first encoding, the sparse array is represented as a valid JSON array with three objects.
  • After unsetting index 1, the sparse array contains a hole, which forces json_encode to convert it to a JSON object to maintain the association between keys and values.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template