2013-04-27 126 views
0

我一直在寻找一段时间,我无法找到一种方法来使其工作。我如何替换stdClass Object数组中的值?例如,如果我有这样的:替换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 
     ) 
) 

在此先感谢您的帮助!

回答

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

+0

谢谢,这样做!我改变了$ v-> vegetable = $ fruit [$ v-> vegetable];'to'$ v-> vegetable = $ vegetable [$ v-> vegetable];' – bsarmi 2013-04-28 20:58:07

0

一个stdClass的对象不是一个数组,它的对象,所以你需要使用对象表示法:

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

读到这里Objects

0

让$阵列是你的磁盘阵列,然后:

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

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

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