php 合并两个二维数组并删除重复行

mm5n2pyu  于 2023-02-03  发布在  PHP
关注(0)|答案(3)|浏览(128)

如何通过合并两个数组并删除任何重复行来创建新的多维数组。
第一个阵列:

[
    0 => ["id" => "0001", "name" => "sample name 1"],
    1 => ["id" => "0002", "name" => "sample name 2"],
    3 => ["id" => "0003", "name" => "sample name 3"]
]

第二个阵列:

[
    0 => ["id" => "0002", "name" => "sample name 2"],
    1 => ["id" => "11323", "name" => "blah blah"]
]

所需结果为:

[
    ["id" => "0001", "name" => "sample name 1"],
    ["id" => "0002", "name" => "sample name 2"],
    ["id" => "0003", "name" => "sample name 3"]
    ["id" => "11323", "name" => "blah blah"]
]
wydwbb8l

wydwbb8l1#

你能做到的

$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)
a6b3iqyw

a6b3iqyw2#

您不需要将数据行减少为序列化字符串来检查唯一性,只需在第二个数组上调用array_udiff(),从其中删除第一个数组行,然后将结果与第一个数组合并。array_udiff()在内部进行了优化,因为它使用排序算法来比较数据--这样,它比in_array()的强力迭代性能更高。
代码:(Demo

$array1 = [
    0 => ["id" => "0001", "name" => "sample name 1"],
    1 => ["id" => "0002", "name" => "sample name 2"],
    3 => ["id" => "0003", "name" => "sample name 3"]
];

$array2 = [
    0 => ["id" => "0002", "name" => "sample name 2"],
    1 => ["id" => "11323", "name" => "blah blah"]
];

var_export(
    array_merge($array1, array_udiff($array2, $array1, fn($a, $b) => $a <=> $b))
);

因为要比较整行,所以还可以合并数组,并将SORT_REGULAR标志与array_unique()一起使用。(Demo

var_export(
    array_unique(array_merge($array1, $array2), SORT_REGULAR)
);
lskq00tm

lskq00tm3#

您可以序列化每个子数组,使用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);
}

相关问题