PHP8.1.21版本已发布
vue8.1.21版本已发布
jquery8.1.21版本已发布

php怎么将json转换成数组

藏色散人
藏色散人 原创
2021-03-22 09:18:59 2374浏览

在php中可以通过json_decode函数将json转换成数组,该函数的作用就是对json格式的字符串进行解码,其语法是“json_decode ( string $json , bool $assoc=false...)”。

本文操作环境:Windows7系统、PHP7.1版,DELL G3电脑

json_decode

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL json >= 1.2.0)

json_decode — 对 JSON 格式的字符串进行解码

说明 

json_decode ( string $json , bool $assoc = false , int $depth = 512 , int $options = 0 ) : mixed

接受一个 JSON 编码的字符串并且把它转换为 PHP 变量

参数 

json

待解码的 json string 格式的字符串。

这个函数仅能处理 UTF-8 编码的数据。

注意:

PHP 实现了 JSON 的一个超集。

assoc

当该参数为 true 时,将返回 array 而非 object 。

depth

指定递归深度。

options

由 JSON_BIGINT_AS_STRING, JSON_INVALID_UTF8_IGNORE, JSON_INVALID_UTF8_SUBSTITUTE, JSON_OBJECT_AS_ARRAY, JSON_THROW_ON_ERROR 组成的掩码。 这些常量的行为在JSON constants页面有进一步描述。

返回值 

通过恰当的 PHP 类型返回在 json 中编码的数据。值true, false 和 null 会相应地返回 true, false 和 null。 如果 json 无法被解码, 或者编码数据深度超过了递归限制的话,将会返回null 。

【推荐学习:PHP视频教程

示例 #1 json_decode() 的例子

<?php
$json = &#39;{"a":1,"b":2,"c":3,"d":4,"e":5}&#39;;
var_dump(json_decode($json));
var_dump(json_decode($json, true));
?>

以上例程会输出:

object(stdClass)#1 (5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}
array(5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}
声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。