hi,欢迎访问本站!
当前位置: 首页编程开发正文

PHP Cannot use object of type stdClass as array 错误

墨初 编程开发 863阅读

在用php操作使用 json_decode() 函数转换的数组时发现了错误,大概的错误就是操作的数据类型不是数组而是对象需要使用stdclass来操作,当然错误的解决方法也有,可以参考下面的博文。

php 数组操作错误提示

PHP Cannot use object of type stdClass as array 

错误翻译

PHP不能将stdClass类型的对象用作数组

php 错误解决方法

上面的错误一般都是由于 json_decode() 函数转换数组时产生的。大概的情况如下。

1、json_decode()将json转为数组时,如果第二个参数不填写则会转对象

json_decode($data);

2、json_decode()将json转为数组时,第二个参数设置为true则会强制将json转为数组

json_decode($data, true);

例1:

json_decode() 第二个参数不设置

$json = '{"name":"mochu","host":"https:\/\/www.73so.com"}'; 
var_dump(json_decode($json));

打印结果

object(stdClass)#3 (2) {
    ["name"]=>
    string(5) "mochu"
    ["host"]=>
    string(20) "https://www.73so.com"
}

例2:

json_decode() 第二个参数设置为true,强制转为数组

$json = '{"name":"mochu","host":"https:\/\/www.73so.com"}';
var_dump(json_decode($json,true));

打印结果

array(2) {
    ["name"]=>
    string(5) "mochu"
    ["host"]=>
    string(20) "https://www.73so.com"
}

以上就是关于php中 Cannot use object of type stdClass as array 错误的解决方法,当然产生此错误的原因也不仅仅是上面所介绍的这种情况,但大概的原因也差不多,个人只需要仔细的查看一下即可。

声明:无特别说明,转载请标明本文来源!
相关推荐