Home > Backend Development > PHP Tutorial > Why Does `json_encode` Sometimes Return a JSON Object Instead of an Array in PHP?

Why Does `json_encode` Sometimes Return a JSON Object Instead of an Array in PHP?

Mary-Kate Olsen
Release: 2024-12-03 08:51:09
Original
744 people have browsed it

Why Does `json_encode` Sometimes Return a JSON Object Instead of an Array in PHP?

Encoding PHP Arrays as JSON Arrays

When converting PHP arrays to JSON using json_encode, you might encounter an issue where the output is an object instead of an array. This discrepancy arises when your array keys are not sequential.

According to the JSON data interchange format, an array is represented as square brackets surrounding values separated by commas:

[value, value, value]
Copy after login

For json_encode to render your array as a JSON array, it must be sequential, meaning its keys should be consecutive integers starting from 0.

Example:

$input = [
    ['id' => 0, 'name' => 'name1', 'short_name' => 'n1'],
    ['id' => 2, 'name' => 'name2', 'short_name' => 'n2']
];
Copy after login

If you attempt to json_encode this array, you will get a JSON object instead of an array:

{
    "0": {
        "id": 0,
        "name": "name1",
        "short_name": "n1"
    },
    "2": {
        "id": 2,
        "name": "name2",
        "short_name": "n2"
    }
}
Copy after login

Solution:

To resolve this issue, you need to reindex your array sequentially using array_values():

$input_sequential = array_values($input);
$json_array = json_encode($input_sequential);
Copy after login

This operation will result in a JSON string representation as an array:

[
    {
        "id": 0,
        "name": "name1",
        "short_name": "n1"
    },
    {
        "id": 2,
        "name": "name2",
        "short_name": "n2"
    }
]
Copy after login

The above is the detailed content of Why Does `json_encode` Sometimes Return a JSON Object Instead of an Array in PHP?. For more information, please follow other related articles on the PHP Chinese website!

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