检查多维中是否存在两对值和键

时间:2014-05-22 18:49:48

标签: php arrays multidimensional-array

$permissions = array(    
    0 => array(  
        "action"   => "CREATE",  
        "subject"  => "USER"  
    ),  
    1 => array(  
        "action"   => "EDIT",  
        "subject"  => "USER"  
    ),   
    2 => array(  
        "action" =>  "DELETE",  
        "subject" => "USER"  
    ),
    3 => array(  
        "action"   => "CREATE",  
        "subject"  => "TASK"  
    ),  
);

我有这段代码来检查" key"之间的组合。和"价值"那里。效果很好。

    public static function verifyPermissions($array, $key, $val) {
    foreach ($array as $item){
        if ( $item[$key] == $val)
            return true;
    }
    return false;
}

以下代码行返回" TRUE",但没有组合" action = EDIT"和" subject = TASK"在数组的同一行。

if(Group::verifyPermissions($permissions,"action","EDIT") && Group::verifyPermissions($permissions,"subject","TASK"))

我需要在数组的同一行同时检查这两个选项。 如何解决此错误?

1 个答案:

答案 0 :(得分:2)

您可以像这样扩展您的功能

public static function verifyTwoPermissions($array, $keys, $values) {
    foreach ($array as $item){
        if ($item[$keys[0]] == $values[0] && $item[$keys[1]] == $values[1])
            return true;
    }
    return false;
}

// verifyTwoPermissions($permissions, array("action", "subject"), array("EDIT", "TASK"))