Home >Backend Development >PHP Tutorial >How to Encode PHP Arrays as JSON Arrays Instead of JSON Objects?

How to Encode PHP Arrays as JSON Arrays Instead of JSON Objects?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-07 18:53:13311browse

How to Encode PHP Arrays as JSON Arrays Instead of JSON Objects?

JSON Arrays vs. JSON Objects: Encoding PHP Arrays for JSON

When dealing with PHP arrays and JSON, it's crucial to understand the distinction between JSON arrays and JSON objects. JSON arrays are represented using square brackets, while JSON objects use curly braces.

In your PHP array, the keys are numeric (0 and 2). However, to be encoded as a JSON array, PHP arrays must have sequential keys starting from 0.

The default behavior of json_encode is to encode your array as a JSON object, which is why you're getting the result you described. To obtain a JSON array instead, you need to reindex your PHP array sequentially using array_values().

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

$output = json_encode(array_values($input));

After reindexing, the output of json_encode will be a valid JSON array, as desired:

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

The above is the detailed content of How to Encode PHP Arrays as JSON Arrays Instead of JSON Objects?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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