json_decode()
把 JSON 字符串解析成 PHP 变量。
json_decode(string $json, ?bool $associative = null, int $depth = 512, int $flags = 0): mixed
参数
| 参数 | 类型 | 说明 |
|---|---|---|
$json | string | JSON 字符串 |
$associative | bool | true 返回数组,false 返回对象,省略时为 null(对象) |
$depth | int | 最大深度 |
$flags | int | JSON_BIGINT_AS_STRING 等 |
返回值
mixed — 解析结果;失败返回 null。
示例
$obj = json_decode('{"a":1}');
echo $obj->a . "\n";
$arr = json_decode('{"a":1}', true);
echo $arr['a'];输出
1 1
注意
- 第二个参数传 true 才是数组,很多人忘了然后报「Cannot use object as array」。
- 解析失败也返回 null,必须用 json_last_error 区分「失败」和「JSON 就是 null」。
- 超过 PHP_INT_MAX 的数字会丢精度,用 JSON_BIGINT_AS_STRING 保留成字符串。