PHP json_decode深度参数不起作用

时间:2013-10-15 19:00:44

标签: php json

PHP的json_decode函数有一个“深度”参数,您可以在其中指定将要递归的深度。但是以下代码:

test = array(
    'name' => 'sean',
    'dob' => '12-20',
    'parents' => array(
        'father' => 'tommy',
        'mother' => 'darcy'
    )
);

foreach(range(1, 3) as $depth) {
    echo "-----------------\n depth: $depth\n";
    print_r(json_decode(json_encode($test), true, $depth));
}

生成此输出:

-----------------
 depth: 1
-----------------
 depth: 2
-----------------
 depth: 3
Array
(
    [name] => sean
    [dob] => 12-20
    [parents] => Array
        (
            [father] => tommy
            [mother] => darcy
        )

)

我期望的是深度为1以显示“name”和“dob”,深度为2以显示父母。我不明白为什么1或2的深度根本没有显示。

任何人都可以向我解释我不理解的事情吗?

3 个答案:

答案 0 :(得分:8)

The documentation说明原因。

  

如果无法解码json,则返回NULL;如果编码数据深于递归限制,则返回

答案 1 :(得分:4)

这里的问题是你没有正确理解depth参数

test数组的深度为3,因此在前两次迭代中不会打印,并返回null

但是在第3次迭代中它被打印,因为它的深度等于$depth [即3]

答案 2 :(得分:1)

除了@Explosion Pills答案外,您希望json_decode能够json_encode工作。

根据文档,您现在可以指定自己的限制来编码数组/对象。这仅仅意味着它将超过指定级别。

对于json_decode它是不同的 - 它总是尝试解析整个JSON字符串,因为它根本无法停止,并且在不解析整个字符串的情况下跳过更深的部分。这就是深度限制导致函数在这种情况下返回NULL的原因。

json_encode可以停止并跳过更深层次的部分,因为数据结构已在内存中定义。

请注意,PHP版本5.5.0已添加$depth json_encode json_decode自5.3.0版以来已添加{{1}}。检查更改日志here