Reputation: 588
I have two arrays:
$to_import = Array(
[0] => Array(['native_id'] => 35339920, ['type'] => product)
[1] => Array(['native_id'] => 22045872, ['type'] => product)
[2] => Array(['native_id'] => 25913185, ['type'] => profile)
[3] => Array(['native_id'] => 14354407, ['type'] => profile)
)
$existing = Array(
[0] => Array(['native_id'] => 22045872)
[1] => Array(['native_id'] => 25913185)
[2] => Array(['native_id'] => 30836971)
)
I need to remove the record from the first array when the id is found in the second array, and when type matches 'profile'. So in this example, three remain:
$to_import = Array(
[0] => Array(['native_id'] => 35339920, ['type'] => product)
[1] => Array(['native_id'] => 22045872, ['type'] => product)
[3] => Array(['native_id'] => 14354407, ['type'] => profile)
)
I have found similar questions, but I can't work out how to apply them to my requirements. This answer looks like it is close to what I want, but I can't get it to work, my knowledge is failing me.
Upvotes: 0
Views: 102
Reputation: 522441
$existing_ids = array_column($existing, 'native_id', 'native_id');
$to_import = array_filter($to_import, function ($item) use ($existing_ids) {
return $item['type'] != 'profile' || !isset($existing_ids[$item['native_id']]);
});
We're creating an array $existing_ids
here which contains all existing ids as its key, so it's extremely quick to look up using isset
. You could use in_array
instead, but it'll be slower. From there it's a pretty simple array_filter
operation.
See http://php.net/array_column. See the comments if you have PHP < 5.5.
Upvotes: 3
Reputation: 59701
This should work for you:
Here I just go through your $to_import
array with array_map()
and check if the key is not in the $keys
array or it is not the type profile
.
<?php
$keys = array_column($existing, "native_id");
$result = array_filter(array_map(function($v)use($keys){
if(!in_array($v["native_id"], $keys) || $v["type"] != "profile")
return $v;
}, $to_import));
print_r($result);
?>
output:
Array
(
[0] => Array
(
[native_id] => 35339920
[type] => product
)
[1] => Array
(
[native_id] => 22045872
[type] => product
)
[3] => Array
(
[native_id] => 14354407
[type] => profile
)
)
Upvotes: 1