Home >Backend Development >PHP Tutorial >Why Does `json_encode` Sometimes Return a JSON Object Instead of an Array in PHP?
When converting PHP arrays to JSON using json_encode, you might encounter an issue where the output is an object instead of an array. This discrepancy arises when your array keys are not sequential.
According to the JSON data interchange format, an array is represented as square brackets surrounding values separated by commas:
[value, value, value]
For json_encode to render your array as a JSON array, it must be sequential, meaning its keys should be consecutive integers starting from 0.
Example:
$input = [ ['id' => 0, 'name' => 'name1', 'short_name' => 'n1'], ['id' => 2, 'name' => 'name2', 'short_name' => 'n2'] ];
If you attempt to json_encode this array, you will get a JSON object instead of an array:
{ "0": { "id": 0, "name": "name1", "short_name": "n1" }, "2": { "id": 2, "name": "name2", "short_name": "n2" } }
Solution:
To resolve this issue, you need to reindex your array sequentially using array_values():
$input_sequential = array_values($input); $json_array = json_encode($input_sequential);
This operation will result in a JSON string representation as an array:
[ { "id": 0, "name": "name1", "short_name": "n1" }, { "id": 2, "name": "name2", "short_name": "n2" } ]
The above is the detailed content of Why Does `json_encode` Sometimes Return a JSON Object Instead of an Array in PHP?. For more information, please follow other related articles on the PHP Chinese website!