This question already has an answer here:
I want to remove all elements from arr2 that have a type contained in arr1:
arr1 = ['A', 'B', 'C']
arr2 = [
[
'name' => 'jane',
'type' => 'X'
],
[
'name' => 'jon',
'type' => 'B'
]
]
So jon should be removed. Is there some built in function like array_diff?
</div>
One of solutions using array_filter
:
print_r(array_filter(
$arr2,
function($v) use($arr1) { return !in_array($v['type'], $arr1); }
));
I don't think there's a way to do it with just one built-in array function, but you can combine some of them to do it.
$record_types = array_column($arr2, 'type');
$records_to_keep = array_diff($record_types, $arr1);
$result = array_intersect_key($arr2, $records_to_keep);
Foreach the 2nd array and check if the type is in arr1. If so then simply delete(unset) it.
foreach(array_keys(arr2) as $Key) {
if (in_array(arr2[$Key]['type'],arr1)) { unset(arr2[$Key]); }
}
Here's another if the type
is unique:
$result = array_diff_key(array_column($arr2, null, 'type'), array_flip($arr1));
$arr2
keyed (indexed) by the type
column$arr1
to get values as keysRun array_values
on it to re-index if needed.