The following works great for me in filtering out my multidimensional array down to the elements I want to focus on…
$mAllLists = []; //my big array
$mFilteredLists = array_filter($mAllLists, function ($data)
{
return $data['stringid'] == "dog" || $data['stringid'] == 'people'
|| $data['stringid'] == 'house' || $data['stringid'] == 'cat';
});
But is possible with array_filter, we can replace $data with a real array that has the keys we want to match against? or is there a better PHP function for that kind of process?
For example, if I had an array that looks like this…
array (
0 =>
array (
'contactList' =>
array (
'stringid' => 'dog',
'status' => '1',
'sourceid' => '0',
),
),
1 =>
array (
'contactList' =>
array (
'stringid' => 'people',
'status' => '1',
'sourceid' => '0',
),
),
)
I would like to use the stringid keys instead of hard coding the $data values for my return in $mFilteredLists.
Is this possible?
2
Answers
After some deep researching and testing things out, I come to the conclusion that it would of been beneficial for me to rename this thread as "How to filter a multidimensional array by multiple key/values of another array".
With that, I found array_walk with a callback useful for my goal. the following example brings me to my goal completely...
The most basic solution is:
Though
in_array
is somewhat slow, an alternative method is:If
VALID_IDS
has to be a variable: