替换stdClass对象数组中的值

时间:2013-04-27 20:48:50

标签: php arrays

我一直在寻找一段时间,我找不到办法让这个工作。如何替换stdClass对象数组中的值?例如,如果我有这个:


Array ( 
    [0] => stdClass Object (
            [id] => 1 
            [fruit] => 100
            [vegetable] => 200
        ) 
    [1] => stdClass Object (
            [id] => 2
            [fruit] => 100
            [vegetable] => 100
        )
    [2] => stdClass Object (
            [id] => 3
            [fruit] => 200
            [vegetable] => 200
        ) 
)

如何更改价值 - 水果100到苹果,水果200到桃,蔬菜100到西兰花,蔬菜200到生菜 - 我需要最终得到这个:


Array ( 
    [0] => stdClass Object (
            [id] => 1 
            [fruit] => apple
            [vegetable] => lettuce
        ) 
    [1] => stdClass Object (
            [id] => 2
            [fruit] => apple
            [vegetable] => broccoli
        )
    [2] => stdClass Object (
            [id] => 3
            [fruit] => peach
            [vegetable] => lettuce
        ) 
)

提前感谢您的帮助!

3 个答案:

答案 0 :(得分:0)

stdClass对象不是数组,它是一个对象,因此您需要使用对象表示法:

$array[0]->id = 'foo';

请在此处阅读Objects

答案 1 :(得分:0)

让$ array成为你的数组,然后:

$array[0]->fruit = 'apple';
$array[0]->vegetable = 'lettuce';

$array[1]->fruit = 'apple';
$array[1]->vegetable = 'broccoli';

$array[2]->fruit = 'peach';
$array[2]->vegetable = 'lettuce';

答案 2 :(得分:0)

你可以尝试

$fruit = array(
        100 => "apple",
        200 => "peach"
);
$vegetable = array(
        100 => "broccoli",
        200 => "lettuce"
);

$final = array_map(function ($v) use($fruit, $vegetable) {
    $v->fruit = $fruit[$v->fruit];
    $v->vegetable = $fruit[$v->vegetable];
    return $v;
}, $arrayObject);

See live DEMO

相关问题