如果其中一个值等于键,则合并两个数组

时间:2014-11-10 13:59:06

标签: php php-5.3

您好我有两个数组一个$ roles和第二个$权限。我想要做的是根据角色中的键合并这两个数组,如果它等于第二个数组的值。我不确定怎么做我尝试使用foreach,但是我坚持检查值并且分配最终结果应该类似于$ rolePermissions。

// Roles indexed by ID
$roles = array(
    1 => 'Administrator',
    2 => 'Moderator',
    3 => 'Admin',
    4 => 'User',
    5 => 'SuperUser',
    6 => 'Accountant',
    7 => 'God'
);

// Permissions indexed by ID
$permissions = array(5) 
[
    0 => array(2) 
        [
            "PermissionName" => string(12) "Catalog-View"
            "RoleId"         => string(2) "22"
        ]
    1 => array(2) 
        [
            "PermissionName" => string(12) "Catalog-View"
            "RoleId"         => string(2) "23"
        ]
    2 => array(2) 
        [
            "PermissionName" => string(12) "Catalog-Edit"
            "RoleId"         => string(2) "22"
        ]
    3 => array(2) 
        [
            "PermissionName" => string(14) "Catalog-Delete"
            "RoleId"         => string(2) "22"
        ]
    4 => array(2) 
        [
            "PermissionName" => string(14) "Article-Delete"
            "RoleId"         => string(2) "22"
        ]
]

// Assign role IDs to permission IDs, array is indexed by role ID
$rolePermissions = array(
    1 => array(1),
    2 => array(1, 2),
    3 => array(1, 2, 3)
);

编辑: 到目前为止我做了什么,但没有得到结果。

foreach ($roles as $key => $value) {
    foreach($permissions as $row) {
        if($key == $row['RoleId'])
            $perm[$key][] = $row;
    }
}

1 个答案:

答案 0 :(得分:1)

<{1>} $roles您的角色ID为1,2,3,4,5,6,7

<{1>} $permissions您的角色ID为22或23

当然永远找不到匹配