2013-01-08 79 views
0

的我有一個數組,看起來像這樣:創建新的密鑰=> value對了現有陣列

Array 
(
    [0] => stdClass Object 
     (
      [food] => Pizza 
      [music] => Rock 
      [color] => blue 
      [name] => John 
     ) 

    [1] => stdClass Object 
     (
      [food] => Toast 
      [music] => Jazz 
      [color] => yellow 
      [name] => Greg 
     ) 

    [2] => stdClass Object 
     (
      [food] => Steak 
      [music] => Classical 
      [color] => green 
      [name] => Steve 
     ) 

    [3] => stdClass Object 
     (
      [food] => Cake 
      [music] => Blues 
      [color] => red 
      [name] => Peter 
     ) 

) 

如何創建一個新的數組,其中結合我的一些內容,以新key => value對,像Peter => Cake

我已經成功地使用一些價值,但它們沒有連接到鑰匙:

$myArr = *The array posted above* 
$newArray = array(); 

foreach ($myArr as $arr) { 
    array_push($newArray, $arr->food); 
} 

回答

1

這將是這樣的:

$newArray = array(); 
foreach ($myArr as $arr) { 
    $newArray[$arr->name] = $arr->food; 
} 

注意,重名被覆蓋與上發生。