PHP:Cannot use object of type stdClass as array

简介: PHP:Cannot use object of type stdClass as array

json数据

$json = '{"name": "Tom", "age": 23}';

反序列化方式一:

$data = json_decode($json);
// 取值方式
// 错误
// print_r($data['name']);
// Cannot use object of type stdClass as array
// 正确
print_r($data->name); // Tom
print_r($data->age); // 23
print_r(gettype($data)); // object
print_r($data);

输出

stdClass Object
(
    [name] => Tom
    [age] => 23
)

反序列化方式二:

$data = json_decode($json, true);
// 取值方式
// 错误
// print_r($data->name);
// Trying to get property of non-object
// 正确
print_r($data['name']); // Tom
print_r($data['age']); // 23
print_r(gettype($data)); // array
print_r($data);

打印结果

Array
(
    [name] => Tom
    [age] => 23
)

参考

出现“Cannot use object of type stdClass as array”

相关文章
|
JSON PHP 数据格式
PHP:json_encode序列化中文字符和json_decode反序列化object
PHP:json_encode序列化中文字符和json_decode反序列化object
68 0
PHP 简单 对象 (object) 与 数组 (array) 的转换
PHP 简单 对象 (object) 与 数组 (array) 的转换
|
PHP
【PHP】[object htmlinputelement]()
【PHP】[object htmlinputelement]()
385 0
【PHP】[object htmlinputelement]()
|
PHP
【PHP】Cannot use object of type stdClass as array
【PHP】Cannot use object of type stdClass as array
381 0
【PHP】Cannot use object of type stdClass as array
|
PHP
php如何遍历多维的stdClass Object 对象,php的转换成数组的函数只能转换外面一丛数组
php如何遍历多维的stdClass Object 对象,php的转换成数组的函数只能转换外面一丛数组  (2012-09-10 19:58:49) 标签:  杂谈 分类: 网页基础知识 php如何遍历多维的stdClass Object 对象,php的转换成数...
1049 0
|
PHP 数据库 关系型数据库
**PHP错误Cannot use object of type stdClass as array in错误的
错误:将PHP对象类型当做了PHP数组  解决方法:用对象操作符-> 今天在PHP输出一个二维数组的时候,出现了“Fatal error: Cannot use object of type stdClass as array in……”。
1179 0
|
JSON PHP 数据格式
PHP“Cannot use object of type stdClass as array” (php在调用json_decode从字符串对象生成json对象时的报错)
php再调用json_decode从字符串对象生成json对象时,如果使用[]操作符取数据,会得到下面的错误错误:Cannot use object of type stdClass as array产生原因: +展开 -PHP     $res = json_decode($res);    $res['key']; //把 json_decode() 后的对象当作数组使用。
1061 0
|
JSON PHP 数据格式
PHP中遍历stdclass object 及 json
原文: PHP中遍历stdclass object 及 json (从网上找的模拟实例)需要操作的数据: $test=Array ( [0] => stdClass Object ( ...
971 0