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

Why Does PHP\'s `json_encode` Convert Sparse Arrays to JSON Objects?

Barbara Streisand
Release: 2024-11-27 08:50:10
Original
489 people have browsed it

Why Does PHP's `json_encode` Convert Sparse Arrays to JSON Objects?

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

Output:

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

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)));
Copy after login
[{
    "abc": "123"
},{
    "nmo": "567"
}]
Copy after login

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!

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