2015-08-14 74 views
0

我一直在试图合并这个数组,其中$array[4]存在多次,例如:$array[4] == 'red'恰好两次。我怎样才能合并这些数组,同时保持其他数据?我已经做了几次尝试,如果要求,我愿意包括我的努力。在多维数组中复制的合并数组

考虑这个数组:

array(3) { 
    [0]=> 
    array(5) { 
       [0]=> 
       string(3) "UID" 
       [1]=> 
       string(3) "532" 
       [2]=> 
       string(1) "2" 
       [3]=> 
       string(9) "Domain(s)" 
       [4]=> 
       string(20) "red" 
      } 
[1]=> 
    array(5) { 
      [0]=> 
       string(3) "UID" 
      [1]=> 
       string(3) "532" 
      [2]=> 
       string(7) "License" 
      [3]=> 
       string(3) "Fee" 
      [4]=> 
       string(20) "red" 
      } 
[2]=> 
    array(5) { 
       [0]=> 
       string(3) "UID" 
       [1]=> 
       string(3) "536" 
       [2]=> 
       string(7) "License" 
       [3]=> 
       string(3) "Fee" 
       [4]=> 
       string(16) " University Test" 
      } 
    } 

努力实现:

array(3) { 
    [0]=> 
    array(5) { 
       [0]=> 
       string(3) "UID" 
       [1]=> 
       string(3) "532" 
       [2]=> 
       string(1) "2" 
       [3]=> 
       string(9) "Domain(s)" 
       [4]=> 
       string(20) " red" 
       [5]=> 
       string(3) "Fee" 
       [6]=> 
       string(7) "License" 
      } 
[1]=> 
    array(5) { 
       [0]=> 
       string(3) "UID" 
       [1]=> 
       string(3) "536" 
       [2]=> 
       string(7) "License" 
       [3]=> 
       string(3) "Fee" 
       [4]=> 
       string(16) " University Test" 
      } 
    } 
+0

是否有你已经尝试任何方法? –

+0

你会得到重复的'key',然后使用'key'移除它。你会在'key'中留下空隙,但是你可以使用'array_values'来重新组织键。 – Script47

+0

结果数组中元素的顺序是否重要? –

回答

1
foreach ($test as $item) { 
    if (!isset($merged[$item[4]])) { 
     // add the item to the merged array using key=$item[4] 
     $merged[$item[4]] = $item; 
    } else { 
     // merge the item with the item that is already in the array at key=$item[4] 
     $merged[$item[4]] = array_unique(array_merge($merged[$item[4]], $item)); 
     // array_unique is necessary because array_merge will not overwrite numeric keys 
    } 
} 
// convert the keys back to numeric (if you care to) 
$merged = array_values($merged); 
+0

这个。工作。谢了哥们。不知道你可以'array_unique(array_merge))'! – Kisaragi