FATAL ERROR未捕获错误:无法使用stdClass类型的对象作为数组

时间:2018-05-30 21:53:32

标签: php

我有一个这样的数组,我从数据库查询得到:

$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 
    )
);

现在我想附加到这个数组并假设它们就像一个100行。我不能手动做到这一点吗?所以我尝试使用这段代码:

foreach($arrname as $key => $value){
    $line = json_decode($value);
    $line['country'] = 'Us';        
    $line['occupation'] = 'Retired';
    $arrname[$key]  = json_encode($line);
}

echo $arrname[0]['country'];

请感谢您的帮助。

2 个答案:

答案 0 :(得分:4)

更改此代码:

foreach($arrname as $key => $value){
$line = json_decode($value);
$line['country'] = 'Us';        
$line['occupation'] = 'Retired';
$arrname[$key]  = json_encode($line);
}

echo $arrname[0]['country'];

到此:

foreach($arrname as $key => $value){
    $line = (array) $value;
    $line['country'] = 'Us';        
    $line['occupation'] = 'Retired';
    $arrname[$key]  = (object) $line;
}

echo $arrname[0]->country;

json_encode函数将数组转换为字符串类型Javascript Object 而且json_decode反之亦然 阅读http://php.net/manual/en/function.json-encode.php

答案 1 :(得分:0)

如果你想要一个物体,你应该像那样使用它

[1] =>  new stdClass Object (
        'name' => 'Logan Pierce',
        'age' => 45,
        'gender' => 'Male'
    )