L.S
L.S

Reputation: 409

Merge two arrays if one of the values equals a key

Hello I have two arrays one $roles and the second $permission. What I would like to do is to merge those two arrays based on the key from roles if it's equal to the value from the second array. I'm not sure how to do it I tried with a foreach, but I got stuck on the checking the value and assigning the end result should be something similar to $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)
);

EDIT: What i did so far but didn't manage getting the result.

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

Upvotes: 0

Views: 464

Answers (1)

David162795
David162795

Reputation: 1866

in $roles you have role IDs of numbers 1,2,3,4,5,6,7

in $permissions you have role IDs of numbers 22 or 23

of course it will never find a match

Upvotes: 1

Related Questions