使用array_filter和function过滤具有多个条件的多维数组

时间:2013-10-05 20:11:43

标签: php arrays

以下是多维数组;从那里我试图过滤掉所有子阵列内容的列表,其中“level”值等于4使用 代码(如下所述);有人可以指导我如何获得相同的列表,其中两个或多个条件应用于相同的代码。

roleid =3 && level = 4 && queryid=59

//array as follows
$Row_Hedder =
Array
(

    [1] => Array
        (
            [username] => Suman
            [roleid] => 3
            [password] => drf123
            [level] => 3
            [queryid] => 59
            [year] => 2013
            [month] => 1
            [date] => 1
            [pagezone11] => 1
            [visiblename] => Suman
            [em1] => 
            [em2] => 
        )

    [2] => Array
        (
            [username] => Pranav
            [roleid] => 3
            [password] => drf123
            [level] => 3
            [queryid] => 59
            [year] => 2013
            [month] => 1
            [date] => 1
            [pagezone11] => 2
            [visiblename] => Pranav
            [em1] => 
            [em2] => 
        )

用于过滤的代码如下所述,

$filter_val1 = 4;

$filter = function($player) use($filter_val1) { return ($player['level'] == $filter_val1); };

$filtered = array_filter($Row_Hedder, $filter);

1 个答案:

答案 0 :(得分:1)

试试这个:

$filter_rules = array(
  'level' => 4,
  'roleid' => 3,
  'queryid' => 59,
);

$filter = function ($player) use ($filter_rules) {
  foreach ($filter_rules as $rulekey => $rulevalue) {
    if ($player[$rulekey] != $rulevalue) {
      return false; 
    }
  }
  return true; 
};

$filtered = array_filter($Row_Hedder, $filter);

闭包检查每个规则,只有当该行满足所有规则时才返回true。