Reputation: 9537
array(
[n] => array(
[mother] => 'some_name',
[children] => [n] => array(
['child_name']=>'some_name'
...
)
)
)
I would like to filter this array using the array_filter(). To filter that array to get only the "records" where the mothers are named "Jane" for instance I do the following which is working like a charm.
array_filter($myarray, function ($k) {
return $k['mother'] == 'Jane';
});
Now I would like to filter $myarray to get the "records" where the children are named "Peter". I tried the following which is not working.
array_filter($myarray, function ($k) {
return $k['children']$k['child_name'] == 'Peter';
});
I also tried the following which is not working either.
array_filter($myarray, function ($k1,$k2) {
return $k1['children']$k2['child_name'] == 'Peter';
});
Upvotes: 0
Views: 2298
Reputation: 259
You have an error inside the array filter callback function:
$myarray = array(
array(
'mother' => 'Jane',
'children' => array(
array('child_name' => 'Peter'),
array('child_name' => 'Peter2')
)
),
array(
'mother' => 'Jane1',
'children' => array(
array('child_name' => 'Peter1'),
)
)
);
//The filtering
$myarray = array_filter($myarray, function ($k) {
//Loop through childs
foreach ($k['children'] AS $child)
{
//Check if there is at least one child with the required name
if ($child['child_name'] === 'Peter')
return true;
}
return false;
});
print_r($myarray);
Upvotes: 3