繁体   English   中英

PHP array_filter-如何在回调函数中使用多个键来array_filter数组?

[英]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'
                               ...
                             )

         )
   )

我想使用array_filter()过滤此数组。 例如,要过滤该数组以仅获取“记录”,其中母亲被命名为“简”,我将执行以下操作,它就像一种魅力。

array_filter($myarray, function ($k) { 
   return $k['mother'] == 'Jane'; 
});

现在,我想过滤$ myarray以获得将孩子命名为“ Peter”的“记录”。 我尝试了以下不起作用的方法。

array_filter($myarray, function ($k) { 
    return $k['children']$k['child_name'] == 'Peter'; 
});

我也尝试了以下方法,这些方法也不起作用。

array_filter($myarray, function ($k1,$k2) { 
    return $k1['children']$k2['child_name'] == 'Peter'; 
});

数组过滤器回调函数内部出现错误:

$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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM