我有两个数组,我想从array2中删除重复记录。我不想在数组2中使用link_id 35记录,因为在array1中存在link_id 35记录,因此它不在array2中显示。
我尝试使用array_map和Unique方法,但效果不佳,因为我认为两个数组的值都不相同。
$array1=
[0] => stdClass Object
(
[link_id] => 35
[link_name] => Test Listerine cool mint packets 3 pack
[alias] => aa
[link_desc] =>
[user_id] => 47
[link_hits] => 103
[link_votes] => 1
[link_rating] => 5.000000
[link_featured] => 0
[link_published] => 1
[link_approved] => 1
[link_template] =>
)
[1] => stdClass Object
(
[link_id] => 373
[link_name] => Test Subject Data Collection Fish Fresh Yellow Tail
[alias] => ba
[link_desc] =>
[user_id] => 47
[link_hits] => 198
[link_votes] => 8
[link_rating] => 2.875000
[link_featured] => 0
[link_published] => 1
[link_approved] => 1
[link_template] =>
)
$array2 =
[0] => stdClass Object
(
[link_id] => 35
[link_name] => Test Listerine cool mint packets 3 pack
[link_desc] =>
[lat] => 0.000000
[lng] => 0.000000
[contactperson] =>
[cat_name] => AA - Made in USA
[link_votes] => 1
[link_rating] => 5.000000
[link_featured] => 0
[value] => 30020864
)
[1] => stdClass Object
(
[link_id] => 541
[link_name] => Test Subject Data Collection Fish Fresh Yellow Tail
[link_desc] =>
[lat] => 25.182573
[lng] => -80.093079
[country] => United States
[postcode] => 33431
[contactperson] => Captain Jack Certified Charters
[cat_name] => BA - Product of USA
[link_votes] => 8
[link_rating] => 2.875000
[link_featured] => 0
[value] => NA
)
答案 0 :(得分:0)
您可以使用array-filter进行操作。首先从第一个数组中提取所有ids
,然后根据这些ID过滤第二个数组。
$arr1 = array( (object) ["link_id"=> 35, "key" => "AAA"], (object) ["link_id"=> 373, "key" => "BBB"]);
$arr2 = array( (object) ["link_id"=> 35, "key" => "CCC"], (object) ["link_id"=> 341, "key" => "DDD"]);
$ids = array_column($arr1, "link_id");
$arr2 = array_filter($arr2, function ($e) use ($ids) {
return !in_array($e->link_id, $ids); //keep him in arr2 only if NOT in ids of arr1
});
更新后的答案更快考虑大量数据(例如@mickmackusa评论)使用此方法
$ids = [];
foreach($arr1 as $e)
$ids[$e->link_id] = true;
$arr2 = array_filter($arr2, function ($e) use ($ids) {
return !isset($ids[$e->link_id]);
});
第一个解决方案在O(n^2)
中,第二个解决方案在O(n)
答案 1 :(得分:0)
这应该在php7中完成。
未经测试的代码:
var_export(array_diff_key(array_column($array2, null, 'link_id'), array_column($array1, null, 'link_id'));
将新的1级密钥分配给两个阵列,然后对这些密钥进行过滤。
检查密钥比迭代调用in_array
更为有效。