繁体   English   中英

如果$ assoc设置为true,json_decode有什么办法可以返回不是数组或null的类型?

[英]Is there any way json_decode can return a type that is not an array or null if $assoc is set to true?

我正在使用php的json_decode解码一些json,但是我一直在获取/ var / log / apache / error_log:PHP致命错误:无法将字符串偏移量用作数组

$data = json_decode($this->body, true);
if (is_null($data))
{
    throw new Exception(...);
}
...
$foo = $data['foo']['bar']; // this line causes the fatal error
...

根据一些研究,导致错误的唯一方法是$ data是字符串。 但是由于$ assoc =为true的json_decode似乎可以保证为null或数组,因此情况并非如此。 任何人都可以以任何方式想到该代码如何导致错误?

当然json_decode可以返回其他类型,而$assoc与它无关。

$a = json_encode('foobar'); // returned JSON: "foobar"
$b = json_decode($a, true); // $b is a string

$a = json_encode(true); // returned JSON: true
$b = json_decode($a, true); // $b is a boolean

$assoc = true仅表示JSON中的对象 (关联数组)将被解码为PHP关联数组,而默认值是将它们解码为PHP对象。 它不会影响JSON中的任何其他类型的数据,因此,如果您的根JSON元素不是数组,则json_decode也将返回非数组。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM