PHP array_filter多回调

时间:2016-09-14 11:22:53

标签: callback array-filter

如何设置multifiltermulticallback

我想要CityConfirm一起过滤数据。

输入数据:

$data1 = array(
            "L1" => array('Vanessa', 'Prague', 'OK'),
            "L2" => array('Alex', 'Paris', 'OK'),
            "L3" => array('Paul', 'Paris', 'OK'),
            "L4" => array('John', 'Madrid', 'OK'),
            "L5" => array('Jane', 'London', 'Waiting'),
            "L6" => array('David', 'Prague', 'OK'),
            "L7" => array('Martin', 'Prague', 'Waiting'),
            "L8" => array('Frank', 'Prague', 'OK'),
            "L9" => array('Joseph', 'Prague', 'Waiting'),
            ); 

过滤代码:

$ByConfirm = 'OK'; 
$ByCity = 'Prague';

以下是我的问题。我尝试使用&&,但它分开工作,我需要$filterByConfirm + $filterByCity的合作

$new = array_filter($data1, $filterByConfirm && $filterByCity);

      $filterByConfirm =  $new = array_filter($data1, function ($var) use ($ByConfirm) {
            return ($var[2] == $ByConfirm); 
      });

      $filterByCity =  $new = array_filter($data1, function ($var) use ($ByCity) {
            return ($var[1] == $ByCity); 
      });

实际结果:

Name    City    Confirm
Vanessa Prague  OK
David   Prague  OK
Martin  Prague  Waiting
Frank   Prague  OK
Joseph  Prague  Waiting

我需要:

Name    City    Confirm
Vanessa Prague  OK
David   Prague  OK
Frank   Prague  OK

1 个答案:

答案 0 :(得分:0)

最后,这是解决方案: PHP 5.2: Filter array with multiple arguments performance

$arrayToCompare = array('type'=>'fruits','has_name'=>'OK', 'has_color'=>'Prague');

$new = array_filter(
                $data1,
                function ($arr) use ($arrayToCompare) { // PHP 5.3 is required here!!
                    return ($arr[2] == $arrayToCompare['has_name']
                        AND $arr[1] == $arrayToCompare['has_color']);
                }
            );