如何组合2个多维数组并删除重复项

时间:2012-09-21 21:20:33

标签: php arrays

如何基于两个数组(在PHP中)创建一个新的多维数组,以便组合数组并删除任何重复项。例如:

第一个阵列:

Array 
(
  [0] => Array
    (
        [id] => 0001
        [name] => sample name 1
    )

  [1] => Array
    (
        [id] => 0002
        [name] => sample name 2
    )
  [3] => Array
    (
        [id] => 0003
        [name] => sample name 3
    )
)

第二阵列:

Array 
(
  [0] => Array
    (
        [id] => 0002
        [name] => sample name 2
    )
  [1] => Array
    (
        [id] => 11323
        [name] => blah blah
    )
)

所以新数组看起来像这样:

Array 
(
  [0] => Array
    (
        [id] => 0001
        [name] => sample name 1
    )

  [1] => Array
    (
        [id] => 0002
        [name] => sample name 2
    )
  [3] => Array
    (
        [id] => 0003
        [name] => sample name 3
    )
  [4] => Array
    (
        [id] => 11323
        [name] => blah blah
    )
)

2 个答案:

答案 0 :(得分:1)

你可以这样做

$array1 = Array(
        0 => Array("id" => "0001","name" => "sample name 1"),
        1 => Array("id" => "0002","name" => "sample name 2"),
        3 => Array("id" => "0003","name" => "sample name 3"));

$array2 = Array(
        0 => Array("id" => "0002","name" => "sample name 2"),
        1 => Array("id" => "11323","name" => "blah blah"));

$output = array_map("unserialize", array_unique(array_map("serialize", array_merge($array1,$array2))));

var_dump($output);

输出

array
  0 => 
    array
      'id' => string '0001' (length=4)
      'name' => string 'sample name 1' (length=13)
  1 => 
    array
      'id' => string '0002' (length=4)
      'name' => string 'sample name 2' (length=13)
  2 => 
    array
      'id' => string '0003' (length=4)
      'name' => string 'sample name 3' (length=13)
  4 => 
    array
      'id' => string '11323' (length=5)
      'name' => string 'blah blah' (length=9)

答案 1 :(得分:0)

您可以序列化每个子阵列,使用array_unique,然后反序列化:

$arr = array_merge($arr1,$arr2);
foreach($arr as &$a) {
    $a = serialize($a);
}
$arr = array_values(array_unique($arr));
foreach($arr as &$a) {
    $a = unserialize($a);
}