php将json转为数组的方法有哪些几种
使用json_decode()函数
在PHP中,json_decode()函数可以方便地将JSON格式的数据转换为PHP数组,具体语法如下:
mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )
参数说明:
$json: 传入一个JSON字符串;$assoc: (可选)默认为false,表示返回一个stdClass对象;若设置为true,则返回一个数组;$depth: (可选)表示递归的最大深度,默认为512层;$options: (可选)设置解码时的选项,常见的有JSON_BIGINT_AS_STRING(将大数字转换成string类型)、JSON_OBJECT_AS_ARRAY(将stdClass对象转换成数组)等。
例如:
$json_str = '{"name":"Jack","age":30,"city":"Beijing"}';
$arr = json_decode($json_str, true);
print_r($arr);
输出结果为:
Array (
[name] => Jack
[age] => 30
[city] => Beijing
)
使用json_decode()函数 + file_get_contents()函数
不仅可以将JSON字符串转为数组,还可以将JSON数据从一个文件中读取,然后将其转换为数组。此时可以使用file_get_contents()函数来读取JSON文件中的内容,再使用上述的json_decode()函数实现转换。
例如:
$json_file = 'data.json';
$json_str = file_get_contents($json_file);
$arr = json_decode($json_str, true);
print_r($arr);
使用json_decode()函数 + curl库
如果JSON数据不在本地文件中,而是通过网络传输过来的,此时可以使用curl库获取JSON数据,然后使用json_decode()函数实现转换。
例如:
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://api.example.com/data.json');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
curl_close($curl);
$arr = json_decode($result, true);
print_r($arr);
上述代码使用了curl库来请求https://api.example.com/data.json接口,将返回的JSON数据转换为数组,并输出结果。