Home >Backend Development >PHP Tutorial >How to Encode PHP Arrays as JSON Arrays Instead of JSON Objects?
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!