合并两个包含对象的数组并删除重复值

2022-08-30 08:22:37

我需要将两个对象数组合并为1个数组并删除重复值。email

我该怎么做?

这些是我的示例数组:

$array1 = [
    (object) ["email" => "gffggfg"],
    (object) ["email" => "wefwef@test.it"],
    (object) ["email" => "wefewf"],
];
$array2 = [
    (object) ["email" => "gffggfg@test.it"],
    (object) ["email" => "wefwef"],
    (object) ["email" => "wefewf"],
];

我的预期结果是:

[
   (object) ['email' => 'gffggfg'],
   (object) ['email' => 'wefwef@test.it'],
   (object) ['email' => 'wefewf'],
   (object) ['email' => 'gffggfg@test.it'],
   (object) ['email' => 'wefwef'],
]

答案 1

您可以将array_merge() 函数与 array_unique() 函数结合使用(两个标题都非常不言自明)

$array = array_unique (array_merge ($array1, $array2));

答案 2

如果我正确理解了这个问题:

 $a1 = Array(1,2,3,4);
 $a2 = Array(4,5,6,7);
 $array =  array_diff(array_merge($a1,$a2),array_intersect($a1,$a2));
 print_r($array);

返回

Array
(
[0] => 1
[1] => 2
[2] => 3
[5] => 5
[6] => 6
[7] => 7
)