Cannot use object of type stdClass as array错误的解决方法
今天调试一个php程序,发现出现了一个没见过的错误,错误代码:Cannot use object of type stdClass as array。这是怎么回事呢?查了半天纵欲发现这个竟然是json的写法问题:
产生原因:
$res = json_decode($res);
$res['key']; //把 json_decode() 后的对象当作数组使用。
网上令狐葱提供了两种解决方法:
1、使用 json_decode($d, true)。就是使json_decode 的第二个变量设置为 true。
2、json_decode($res) 返回的是一个对象, 不可以使用 $res['key'] 进行访问, 换成 $res->key 就可以了。
参考手册:json_decode
Return Values:Returns an object or if the optional assoc parameter is TRUE, an associative array is instead returned.
本文介绍了在PHP中遇到的Cannot use object of type stdClass as array错误的原因及解决方法。该错误通常发生在尝试将JSON解码为数组而非对象时。文中提供了两种解决方案:一是使用json_decode的第二个参数设置为true;二是改变访问方式,使用$obj->key而非$obj['key']。
3316

被折叠的 条评论
为什么被折叠?



