简体   繁体   English

替换stdClass对象数组中的值

[英]Replacing values in a stdClass Object array

I've been looking for a while and I can't find a way to get this to work. 我已经寻找了一段时间,但找不到使它正常工作的方法。 How can I replace values in a stdClass Object array? 如何替换stdClass对象数组中的值? For example if I have this: 例如,如果我有这个:


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

How do I change the values - fruit 100 to apple, fruit 200 to peach, vegetable 100 to broccoli and vegetable 200 to lettuce - I need to end up with this: 如何更改值-水果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
        ) 
)

Thanks in advance for any help! 在此先感谢您的帮助!

A stdClass Object is not an array, its an object so you need to use object notation: stdClass对象不是数组,而是一个对象,因此您需要使用对象表示法:

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

read here Objects 在这里阅读对象

Lets $array be your array, then: 让$ 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';

You can try 你可以试试

$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 观看现场演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM