关于json_decode转换json对象为数组的一个坑

今天在写一个小玩意的时候,使用了json_decode来处理一段返回结果。当我直接调用转换后数组下标的时候,提示如下错误。

PHP Fatal error: Cannot use object of type stdClass as array in *:\*.php on line *

于是乎,前往php.net关于json_decode的页面查看文档。
发现json_decode完整用法如下。

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

上面问题的原因就在于第二个参数assoc,文档内的解析是——当该参数为 TRUE 时,将返回 array 而非 object

真相大白,刚刚我们操作并没有加上这个参数,而这个参数默认为false。所以操作的是一个对象而不是一个数组,自然会出错。

以php.net的示例代码结束本文。

例子:
<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
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)
}

关于json_decode转换json对象为数组的一个坑
https://blog.loststar.tech/posts/d646a445/
作者
Loststar
发布于
2017年8月5日
许可协议