Compute (set) difference between arrays in PHP?
I going to implement ACL (Access control list) in my php website.
In my system user have sum a of roles and permission.
Main algorithm is as follows:
permissions = (permissions_by_role + permission_for_user) - user_banned_permission
so I have three arrays and get those values from database.
For the first part I use this
$permissions = array_unique(array_m开发者_开发知识库erge($permission_by_role, $permission_by_user));
How can I remove my banned permission from permission array? Now I have these two arrays:
$permissions and $permission_banned_for_user[]
sounds like a perfect use-case for array_diff:
$permissions = array_diff($permissions, $permission_banned_for_user);
What you need is array_diff() - Compares array1 against array2 and returns the difference.
$allowed = array('view', 'create', 'edit', 'delete', 'add');
$banned = array('add', 'delete');
$result = array_diff($allowed, $banned);
print_r($result); //Array ( [0] => view [1] => create [2] => edit )
If I am understanding the situation correctly you can do this easily by using the array_diff() function. Have a look here: http://www.php.net/manual/en/function.array-diff.php
This will take 2 arrays and return all elements that are in array 1 and not in array 2.
精彩评论