Reputation: 359
I have a multidimensional array containing child arrays in the following format:
[0] Array =>
(
[first] => Foo
[second] => Bar
)
[1] Array =>
(
[first] => Foo
[second] => Bar
)
[2] Array =>
(
[first] => Foo
[second] => bingo
)
[3] Array =>
(
[first] => jackpot
[second] => bar
)
I would like to search the entire array for 'bingo' and 'jackpot' and remove any child arrays that do not contain these values (in the above example, array 0 and array 1 should be removed).
I understand how to search the array using array_search('bingo', $myarray) but not how to remove the other two. Is there a simple way to achieve this?
Upvotes: 1
Views: 1004
Reputation: 59681
This should work for you:
(Here I just filter all arrays out with array_filter()
which does have an element with either jackpot
or bingo
in it, so only the arrays which doesn't have either jackpot
or bingo
in it will remain. After this I get all keys of these arrays with array_keys()
and loop through them and unset they arrays)
<?php
$keys = array_keys(array_filter($arr, function($v, $k){
if(in_array("jackpot", $v) || in_array("bingo", $v) )
return FALSE;
return TRUE;
}, ARRAY_FILTER_USE_BOTH));
foreach($keys as $key)
unset($arr[$key]);
print_r($arr);
?>
output:
Array
(
[2] => Array
(
[first] => Foo
[second] => bingo
)
[3] => Array
(
[first] => jackpot
[second] => bar
)
)
EDIT:
Even a simpler solution would be just to do this:
foreach($arr as $k => $v) {
if(!in_array("jackpot", $v) && !in_array("bingo", $v))
unset($arr[$k]);
}
Upvotes: 3