2011-11-26 52 views
4

我有三個陣列,某種層次的預定義項PHP array_walk多維數組

array("fruits", "yellow", "pineapple"); 
array("fruits", "yellow", "lemon"); 
array("fruits", "red", "apple"); 

和我有有一種層次結構的assoc命令數組:

array('fruits'=>array('red'=>array('tomato'))); 

我怎麼能推我的三個陣列的條款在我得到的正確位置:

array('fruits'=>array('yellow'=>array('pineapple','lemon'),'red'=>array('tomato','apple'))); 

我使用array_walk?或者array_walk_recursive? 我應該使用什麼?

最佳,約爾格

回答

3

您將每個水果轉換爲嵌套數組,然後使用array_merge_recursive()進行合併。

這裏的工作示例(also on Codepad):

$fruits = array(
    array("fruits", "yellow", "pineapple"), 
    array("fruits", "yellow", "lemon"), 
    array("fruits", "red", "apple"), 
    array("fruits", "red", "tomato"), 
); 

// Convert array to nested array 
function nest($leaf) 
{ 
    if (count($leaf) > 1) 
    { 
    $key = array_shift($leaf); 

    return array($key => nest($leaf)); 
    } 
    else 
    { 
    return $leaf; 
    } 
} 

$tree = array(); 

foreach($fruits as $fruit) 
{ 
    // Convert each fruit to a nested array and merge recursively 
    $tree = array_merge_recursive($tree, nest($fruit)); 
} 

print_r($tree); 
+0

謝謝!而已!你讓我今天一整天都感覺很好 :-) – user987875

1
$fruits[] = array("fruits", "yellow", "pineapple"); 
$fruits[] = array("fruits", "yellow", "lemon"); 
$fruits[] = array("fruits", "red", "apple"); 

foreach($fruits as $fruit) { 
    $multifruit[$fruit[0]][$fruit[1]][] = $fruit[2]; 
} 

print_r($multifruit); 

/* yields: 
Array 
(
    [fruits] => Array 
     (
      [yellow] => Array 
       (
        [0] => pineapple 
        [1] => lemon 
       ) 

      [red] => Array 
       (
        [0] => apple 
       ) 

     ) 

) 
*/ 

不正是你想要的。分配左側的最後一個[]附加右側,而不是覆蓋任何現有值(如果存在)。

+0

我唯一的問題是這個答案是它不足以處理更長或更短的數組。如果你給它一個數組('水果','黃色','蘋果','奶奶史密斯')'? –

0
<?php 

$fruits[] = array("fruits", "yellow", "pineapple"); 
$fruits[] = array("fruits", "yellow", "lemon"); 
$fruits[] = array("fruits", "red", "apple"); 
$fruits[] = array("fruits", "blue", "small","blueberry"); 
$fruits[] = array("fruits", "blue", "bluefruit"); 
$fruits[] = array("fruits", "multicolor-fruit"); 

function deeper(&$multifruit, $fruit) { 
    if (count($fruit)>2) { 
     $shifted = array_shift($fruit); 
     deeper($multifruit[$shifted], $fruit); 
     return $multifruit; 
    } else { 
     return $multifruit[$fruit[0]][] = $fruit[1]; 
    } 
} 

foreach($fruits as $fruit) { 
    deeper($multifruit, $fruit); 
} 

print_r($multifruit); 
?> 

在這裏,你跟你的問題更爲通用的解決方案。我花了一段時間,所以我希望你感激它:)