Home >Backend Development >PHP Tutorial >How Can I Ensure My PHP Array Encodes as a JSON Array, Not an Object?

How Can I Ensure My PHP Array Encodes as a JSON Array, Not an Object?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-26 02:42:09313browse

How Can I Ensure My PHP Array Encodes as a JSON Array, Not an Object?

Encoding PHP Arrays as JSON Arrays

The dilemma of converting a PHP array into a JSON array instead of an object arises when the PHP array has non-sequential keys. By default, json_encode() interprets arrays as objects if the keys are not sequential.

To address this issue, it's crucial to understand the JSON RFC 8259 specification. It defines an array as square brackets enclosing values separated by commas. Therefore, to generate a JSON array, the PHP array must have consecutive numeric keys (0, 1, 2, ...).

In the given example, the PHP array has keys 0 and 2 but not 1. This non-sequential key structure causes json_encode() to treat the array as an object.

To rectify this and encode the array as a JSON array, one must reindex it sequentially using array_values(). This function creates a new array with consecutive numeric keys, effectively transforming the original array into a format acceptable for JSON encoding.

The following code snippet demonstrates how to use array_values() to achieve the desired result:

echo json_encode(array_values($input));

The above is the detailed content of How Can I Ensure My PHP Array Encodes as a JSON Array, Not an Object?. 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