Home > Backend Development > PHP Tutorial > How Do I Convert a PHP Array to a JSON Array Using `json_encode`?

How Do I Convert a PHP Array to a JSON Array Using `json_encode`?

Patricia Arquette
Release: 2024-12-03 13:12:12
Original
604 people have browsed it

How Do I Convert a PHP Array to a JSON Array Using `json_encode`?

Converting PHP Array to JSON Array Using json_encode

When working with PHP arrays, it's important to understand how they are represented in JSON when using json_encode. By default, PHP arrays are encoded as JSON objects when their keys are not sequential.

Consider the following PHP array:

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

When attempting to encode this array using json_encode, the result would be the following JSON object:

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

This behavior occurs because the array keys are non-sequential (0 and 2). To encode the array as a JSON array, all keys must be sequential.

Solution: Reindexing with array_values

To convert the array to a sequential format, use the array_values function:

$output = json_encode(array_values($input));
Copy after login

This reindexes the array, starting with 0, ensuring sequential keys. The resulting JSON becomes an array:

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

By understanding PHP array representation in JSON and using array_values for sequential reindexing, you can successfully encode PHP arrays as JSON arrays using json_encode.

The above is the detailed content of How Do I Convert a PHP Array to 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