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

时间:2014-02-24 16:16:53

标签: php arrays array-filter

  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'; 
});

1 个答案:

答案 0 :(得分:3)

数组过滤器回调函数中有错误:

$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);