1

如何基于两个数组(在 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
    )
)
4

2 回答 2

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)
于 2012-09-21T21:38:37.277 回答
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);
}
于 2012-09-21T21:34:20.970 回答