[英]FATAL ERROR Uncaught Error: Cannot use object of type stdClass as array
I have an array such as this which I get from a database query: 我有一个这样的数组,我从数据库查询得到:
$arrname
Array (
[0] => stdClass Object (
[name] => Mike teach
[age] => 67
[gender] => Male
)
[1] => stdClass Object (
[name] => Logan Pierce
[age] => 45
[gender] => Male
)
[2] => stdClass Object (
[name] => Erikka Menh
[age] => 60
[gender] => Female
)
);
Now I want to append to this array and assuming they were like a 100 rows. 现在我想追加到这个数组并假设它们像100行。 I can't do that manually right?
我不能手动做到这一点吗? So I tried using this code:
所以我尝试使用这段代码:
foreach($arrname as $key => $value){
$line = json_decode($value);
$line['country'] = 'Us';
$line['occupation'] = 'Retired';
$arrname[$key] = json_encode($line);
}
echo $arrname[0]['country'];
Please I'd appreciate some help. 请帮助我。
change this code: 更改此代码:
foreach($arrname as $key => $value){
$line = json_decode($value);
$line['country'] = 'Us';
$line['occupation'] = 'Retired';
$arrname[$key] = json_encode($line);
}
echo $arrname[0]['country'];
to this: 对此:
foreach($arrname as $key => $value){
$line = (array) $value;
$line['country'] = 'Us';
$line['occupation'] = 'Retired';
$arrname[$key] = (object) $line;
}
echo $arrname[0]->country;
the json_encode function convert the array to a string type Javascript Object and json_decode does viceversa read http://php.net/manual/en/function.json-encode.php json_encode函数将数组转换为字符串类型Javascript Object,而json_decode则反之亦然,请阅读http://php.net/manual/en/function.json-encode.php
If you wanna have a objects, you should use it like that 如果你想要一个物体,你应该这样使用它
[1] => new stdClass Object (
'name' => 'Logan Pierce',
'age' => 45,
'gender' => 'Male'
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.