In PHP development, we often need to process JSON strings, and sometimes we need to convert JSON strings into JSON arrays. Today we will learn how to convert JSON string to JSON array in PHP.
PHP provides a very simple function - json_decode(), which is used to convert JSON strings into PHP objects or arrays.
Syntax:
mixed json_decode ( string $json [, bool $assoc = FALSE [, int $depth = 512 [, int $options = 0 ]]] )
Parameters:
Example:
$json_string = '{"name": "Tom","age": 18,"gender": "male"}'; $json_array = json_decode($json_string, true); print_r($json_array);
Output:
Array ( [name] => Tom [age] => 18 [gender] => male )
In the above example, $json_array is a JSON array.
If the JSON string contains a two-dimensional array, we can set the assoc parameter to false and then pass json_decode( ) function parses to get an object of type stdClass, and then you can use the object properties to get the value.
Example:
$json_string = '[{"name": "Tom","age": 18,"gender": "male"},{"name": "Alice","age": 20,"gender": "female"}]'; $json_array = json_decode($json_string, false); echo $json_array[0]->name;
Output:
Tom
In the above example, $json_array[0]->name is the name attribute of the first element in the JSON array value.
If we want to convert JSON string to PHP object instead of array, we can set the assoc parameter to false , or do not pass this parameter.
Example:
$json_string = '{"name": "Tom","age": 18,"gender": "male"}'; $json_object = json_decode($json_string); echo $json_object->age;
Output:
18
In the above example, $json_object is a PHP object, and we can use object properties to get the value.
Summary
This article introduces two methods of converting JSON strings to JSON arrays in PHP: using the json_decode() function to parse key-value pair arrays and multi-dimensional arrays, and converting JSON characters Convert string to PHP object.
No matter which method is used, you can convert the JSON string into a JSONArray, and then use PHP to obtain the JSON data, which will help us process the data better and develop better applications.
The above is the detailed content of Convert json string to json array php. For more information, please follow other related articles on the PHP Chinese website!