验证码: 看不清楚,换一张 查询 注册会员,免验证
  • {{ basic.site_slogan }}
  • 打开微信扫一扫,
    您还可以在这里找到我们哟

    关注我们

php将json转为数组的方法有哪些几种

阅读:846 来源:乙速云 作者:代码code

php将json转为数组的方法有哪些几种

  1. 使用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
)

  1. 使用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);

  1. 使用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数据转换为数组,并输出结果。

分享到:
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: hlamps#outlook.com (#换成@)。
相关文章
{{ v.title }}
{{ v.description||(cleanHtml(v.content)).substr(0,100)+'···' }}
你可能感兴趣
推荐阅读 更多>