PHP is a powerful back-end language that is often used to process data, including processing data in JSON format. JSON is a lightweight data interaction format that is often used to transfer data between different platforms. In PHP, you can convert a JSON string to an array or object. This article will explain how to convert a JSON string into an array of objects.
The json_decode() function in PHP is used to convert JSON strings into objects or arrays. Its basic syntax is as follows:
mixed json_decode ( string $json [, bool $assoc = FALSE [, int $depth = 512 [, int $options = 0 ]]] )
The first parameter is the JSON string to be decoded. . The second parameter is an optional option used to specify whether to convert the converted object into an associative array, and the default is to return the object. The third parameter depth represents the maximum recursion depth, while the fourth parameter options represents conversion options.
Sample code:
$json_str = '{"name":"John", "age":30, "city":"New York"}'; $obj = json_decode($json_str); echo $obj->name; // 输出 John echo $obj->age; // 输出 30 echo $obj->city; // 输出 New York $arr = json_decode($json_str, true); echo $arr["name"]; // 输出 John echo $arr["age"]; // 输出 30 echo $arr["city"]; // 输出 New York
This code first defines a JSON string, then calls the json_decode() function to convert it into an object $obj, and the associative array $arr by default, and output the converted value.
It is worth noting that when there are nested arrays in the JSON string, it will be very complicated. In this case, you can convert it into an object first, and then traverse the objects in it. The following sample code demonstrates how to access nested data in JSON:
$json_str = '{"name":"John", "age":30, "city":"New York", "Hobby":["Reading", "Basketball", "Coding"]}'; $obj = json_decode($json_str); foreach ($obj->Hobby as $hobby) { echo $hobby . "<br>"; // 输出 Reading Basketball Coding } $arr = json_decode($json_str, true); foreach ($arr["Hobby"] as $hobby) { echo $hobby . "<br>"; // 输出 Reading Basketball Coding }
The above code defines a JSON string containing nested data, and traverses the Hobby attribute in it. You can also select Convert it to an associative array and then traverse it.
Summary: When processing JSON data, it is very convenient to use the json_decode() function to convert it into an object or array, but you need to pay attention to the nesting situation that occurs in the JSON string. Through PHP's related functions, you can easily process data in JSON format. I hope this article can help PHP developers better interact with data.
The above is the detailed content of How to convert JSON string to object array in php. For more information, please follow other related articles on the PHP Chinese website!