2013-04-27 130 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';