简体   繁体   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?

I am using php's json_decode to decode some json, but i've been getting a /var/log/apache/error_log:PHP Fatal error: Cannot use string offset as an array 我正在使用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
...

Based on some research, the only way that can cause the error is if $data is a string. 根据一些研究,导致错误的唯一方法是$ data是字符串。 but since json_decode with $assoc = to true seems to guarantee null or an array, that should not be the case. 但是由于$ assoc =为true的json_decode似乎可以保证为null或数组,因此情况并非如此。 Can anyone think of any way how that code could possibly cause an error? 任何人都可以以任何方式想到该代码如何导致错误?

Of course json_decode can return other types, and $assoc has nothing to do with it. 当然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 only means that objects (associative arrays) in the JSON will be decoded as PHP associative arrays, while the default is to decode them as PHP objects. $assoc = true仅表示JSON中的对象 (关联数组)将被解码为PHP关联数组,而默认值是将它们解码为PHP对象。 It does not affect any other type of data in the JSON, so if your root JSON element is not an array, the json_decode will return non-array too. 它不会影响JSON中的任何其他类型的数据,因此,如果您的根JSON元素不是数组,则json_decode也将返回非数组。

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

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