Home >Backend Development >PHP Problem >How to convert object array into json string array in php
Converting an array of objects to a JSON string array is a very common task in PHP. This is very useful when working with data as we can send the data to the front end or other programs. In this article, we will learn how to convert an array of objects into a JSON array of strings.
JSON is a lightweight data exchange format that can pass data from one place to another. Therefore, converting an array of PHP objects to an array of JSON strings is very useful as we can easily send it to other applications or frontends when needed.
First, we need to create an array of sample objects to demonstrate in this article how to convert it to a JSON string array. The following is a sample code that contains three objects:
$objects = [ [ 'name' => 'John', 'age' => 28, 'city' => 'New York', ], [ 'name' => 'Alice', 'age' => 32, 'city' => 'Paris', ], [ 'name' => 'Bob', 'age' => 22, 'city' => 'London', ], ];
The above example array contains three objects, each containing name
, age
, and city
properties. Now we need to convert this into a JSON string array.
PHP provides the json_encode()
function, which converts PHP objects and arrays into JSON strings. However, this function can only convert an object or array into a JSON string. Therefore, we need to loop through each object and convert it into a JSON string array.
The following is a sample code:
$jsonStrings = []; foreach ($objects as $object) { $jsonStrings[] = json_encode($object); }
In the above code, we first define an empty array named $jsonStrings
. We then use foreach
to loop through each object and convert it to a JSON string using the json_encode()
function. Finally, we add the JSON string to the $jsonStrings
array using the []
operator.
Now, we can use the print_r()
function to print the $jsonStrings
array to see the resulting JSON string array. The following is the sample code:
print_r($jsonStrings);
The output is as follows:
Array ( [0] => {"name":"John","age":28,"city":"New York"} [1] => {"name":"Alice","age":32,"city":"Paris"} [2] => {"name":"Bob","age":22,"city":"London"} )
As shown above, we have successfully converted the object array into a JSON string array. Now we can send it to the frontend or other applications when needed.
In this article, we learned how to convert an array of objects into a JSON array of strings. Using the steps above, you can easily convert an array of PHP objects into a JSON string array and send it to other applications or frontends when needed.
The above is the detailed content of How to convert object array into json string array in php. For more information, please follow other related articles on the PHP Chinese website!