开发者

Compute (set) difference between arrays in PHP?

开发者 https://www.devze.com 2023-04-06 09:55 出处:网络
I going to implement ACL (Access control list) in my php website. In my system user have sum a of roles and permission.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号