Encoding PHP Arrays as JSON Arrays with json_encode
In PHP, the json_encode function is used to convert PHP data structures into their JSON counterparts. By default, PHP arrays are encoded as JSON objects. However, there are scenarios where encoding an array as a JSON array is necessary.
Problem Statement
Consider the PHP array below:
$array = [ [ "id" => 0, "name" => "name1", "short_name" => "n1" ], [ "id" => 2, "name" => "name2", "short_name" => "n2" ] ];
Upon calling json_encode on this array, the resulting JSON is an object:
{ "0": { "id": 0, "name": "name1", "short_name": "n1" }, "2": { "id": 2, "name": "name2", "short_name": "n2" } }
This is not the desired output since we want a JSON array instead.
Solution
To encode a PHP array as a JSON array, the array must be sequential, meaning its keys must be consecutive integers starting from 0. In the provided example, the array keys are 0 and 2, which is not sequential.
To make the array sequential, we can use the array_values function:
echo json_encode(array_values($array));
This will reindex the array sequentially, producing the following JSON output:
[ { "id": 0, "name": "name1", "short_name": "n1" }, { "id": 2, "name": "name2", "short_name": "n2" } ]
By ensuring that the array is sequential, json_encode correctly encodes it as a JSON array.
The above is the detailed content of How to Encode a PHP Array as a JSON Array Using `json_encode`?. For more information, please follow other related articles on the PHP Chinese website!