2016-12-14 143 views
0

我有4個數組,我需要通過按鍵結合「0」:結合陣列,相同的密鑰

Array 
    (
    [0] => 1 
    [1] => Array 
    (
     [0] => A 
     [1] => B 
     [2] => C 
    ) 

) 

Array 
    (
    [0] => 2 
    [1] => Array 
    (
     [0] => D 
     [1] => E 
     [2] => F 
    ) 

) 


Array 
    (
    [0] => 1 
    [1] => Array 
    (
     [0] => G 
     [1] => H 
     [2] => I 
    ) 

) 


Array 
    (
    [0] => 2 
    [1] => Array 
    (
     [0] => J 
     [1] => K 
     [2] => L 
    ) 

) 

我需要得到的是組合陣列看起來應該像這樣的:

Array 
    (
    [0] => 1 
    [1] => Array 
    (
     [0] => A 
     [1] => B 
     [2] => C 
     [3] => G 
     [4] => H 
     [5] => I 
    ) 

) 

Array 
    (
    [0] => 2 
    [1] => Array 
    (
     [0] => D 
     [1] => E 
     [2] => F 
     [3] => J 
     [4] => K 
     [5] => L 
    ) 

) 

我試着用array_merge_recursive但沒有成功。 也在這裏搜索,對不起,如果重複 在此先感謝幫助!

+1

_sorry如果duplicated_?如果重複,然後使用原帖的答案,而不是轉貼 –

+0

我提到我已經搜索,但無法找到 – Pecooou

回答

0

試試這個:

$init = array(
    array(1, array('A', 'B', 'C')), 
    array(2, array('D', 'E', 'F')), 
    array(1, array('G', 'H', 'I')) 
); 

$results = array(); 

foreach ($init as $array){ 
    $found = false; 
    foreach ($results as &$result){ 
     if ($array[0] === $result[0]){ 
      $result[1] = array_merge($result[1], $array[1]); 
      $found = true; 
     } 
    } 
    if (!$found){ 
     $results[] = $array; 
    } 
} 
+0

爲什麼要OP「試試這個」?一個好的答案**將總是解釋所做的事情以及爲什麼這樣做,不僅是爲了OP,而且是爲了將來SO的訪問者。 –