[英]PHP array_filter - How to array_filter arrays using multiple keys in the callback function?
array(
[n] => array(
[mother] => 'some_name',
[children] => [n] => array(
['child_name']=>'some_name'
...
)
)
)
I would like to filter this array using the array_filter(). 我想使用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". 现在,我想过滤$ myarray以获得将孩子命名为“ 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';
});
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.