In the process of web development, we often need to convert JSON data format into arrays. The PHP language has a good ability to process JSON and can quickly convert data in JSON format into an array.
In PHP, there are built-in json_decode() function and json_encode() function to convert between JSON and arrays. Below we will introduce how to use these two functions respectively.
1. json_decode() function
json_decode() function is used to convert JSON data format into PHP array. Its syntax is as follows:
mixed json_decode ( string $json [, bool $assoc = FALSE [, int $depth = 512 [, int $options = 0 ]]] )
Among them, the json parameter is the JSON string to be converted; the assoc parameter is used to specify whether the return value is an object or an array, and the default is an array; the depth parameter is used to set the maximum nesting depth , the default value is 512; the options parameter is used to set encoding options and is usually not needed.
The following is an example of converting a JSON string into an array:
$json_str = '{"name":"Tom","age":18}'; $arr = json_decode($json_str, true); print_r($arr);
The output of the above code is:
Array ( [name] => Tom [age] => 18 )
2. json_encode() function
# The ##json_encode() function is used to convert a PHP array into a JSON format string. Its syntax is as follows:string json_encode ( mixed $value [, int $options = 0 [, int $depth = 512 ]] )
$arr = array('name' => 'Tom', 'age' => 18); $json_str = json_encode($arr); echo $json_str;
{"name":"Tom","age":18}
$json_str = '[{"name":"Tom","age":18},{"name":"Jack","age":20},{"name":"Mary","age":22}]'; $arr = json_decode($json_str, true); echo $arr[1]['name'];
Jack
The above is the detailed content of json to array php. For more information, please follow other related articles on the PHP Chinese website!