Home > Backend Development > PHP Tutorial > How to Encode a PHP Array as a JSON Array Using `json_encode`?

How to Encode a PHP Array as a JSON Array Using `json_encode`?

Barbara Streisand
Release: 2024-12-21 18:51:10
Original
590 people have browsed it

How to Encode a PHP Array as a JSON Array Using `json_encode`?

Encoding PHP Arrays as JSON Arrays with json_encode

In PHP, the json_encode function is used to convert PHP data structures into their JSON counterparts. By default, PHP arrays are encoded as JSON objects. However, there are scenarios where encoding an array as a JSON array is necessary.

Problem Statement

Consider the PHP array below:

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

Upon calling json_encode on this array, the resulting JSON is an object:

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

This is not the desired output since we want a JSON array instead.

Solution

To encode a PHP array as a JSON array, the array must be sequential, meaning its keys must be consecutive integers starting from 0. In the provided example, the array keys are 0 and 2, which is not sequential.

To make the array sequential, we can use the array_values function:

echo json_encode(array_values($array));
Copy after login

This will reindex the array sequentially, producing the following JSON output:

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

By ensuring that the array is sequential, json_encode correctly encodes it as a JSON array.

The above is the detailed content of How to Encode a PHP Array as a JSON Array Using `json_encode`?. 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