根据值 php 查找数组中的差异



我有 2 个数组 -

Array
(
[0] => Array
(
[description] => 5390BF675E1464F32202B
[to_email] => test@test.com
)
[1] => Array
(
[description] => 5390BF675E1464F32202B
[to_email] => test3@test.com
)
[2] => Array
(
[description] => 5390BF675E1464F32202B
[to_email] => testagain@gmail.com
)
)
Array
(
[0] => Array
(
[to_email] => test@test.com
)
[1] => Array
(
[to_email] => test3@test.com
)
)

我想从数组 1 中获取与第二个数组不同的值。

我试过使用 -

$result = array_diff_assoc($array1, $array2);

$result = array_diff($array1, $array2);

但两者都给出了错误,比如——

注意:数组到字符串的转换

我期待的结果是

Array
(
[0] => Array
(
[description] => 5390BF675E1464F32202B
[to_email] => testagain@gmail.com
)
)

您可以使用array_column生成要排除的电子邮件地址列表。我们使用 3 参数形式按电子邮件地址对该数组进行索引,因为它可以更轻松地过滤:

$exclude_ids = array_column($array2, 'to_email', 'to_email');

然后我们可以使用array_filter来过滤$array1

$output = array_filter($array1, function ($v) use ($exclude_ids) {
return !isset($exclude_ids[$v['to_email']]);
});
print_r($output);

输出:

Array
(
[2] => Array
(
[description] => 5390BF675E1464F32202B
[to_email] => testagain@gmail.com
)    
)

3v4l.org 演示

请注意,如果您希望将输出数组重新索引为 0,只需使用

$output = array_values($output);

最新更新