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!