问题描述
define('PLAN_A',0); // 0001
define('PLAN_B',2); // 0010
define('PLAN_C',4); // 0100
define('PLAN_D',8); // 1000
define('PLAN_E',16); // 10000
$user_one = array(PLAN_A,PLAN_C); // is subscribed to two plans
$user_two = array(PLAN_C); // is only subscribed to one plan
“流程”需要特定的订阅计划级别 - 或多个计划级别:
$process_1 = array(PLAN_B); // requires only PLAN_B subscripton
$process_2 = array(PLAN_B,PLAN_D); // requires either PLAN_B or PLAN_C subscription
我想检查 $user_one
是否具有访问 $process_1
的“权限”,并单独检查 $user_one
是否具有访问 $process_2
的权限。并对 $user_two
进行同样的检查。 (“权限”是指用户是否拥有流程所需的订阅计划。)
看起来我需要检查流程的订阅要求中是否包含任何用户计划订阅(一个或多个)。
我尝试使用按位检查(这就是 PLAN 具有二进制值的原因),但这仅适用于 $process_1
的检查。我如何检查 $user_1
是否可以访问 $process_2
?或者,如何检查用户数组的任何值是否包含在流程需求数组的任何值中?
解决方法
你可以使用一些函数来完成这项工作,就像这样:
function UserPlanHaveRequiredSub($user_plans,$process): bool
{
foreach($user_plans as $plan){
if (in_array($plan,$process)){
return true;
}
}
return false;
}
然后你可以像这样传递用户计划和流程:
$result = UserPlanHaveRequiredSub($user_one,$process_2 );
var_dump($result);// will return true or false .
,
由于其中一个用户 (jirarium) 复制了我的评论并将其作为答案发布,我不妨自己做,并实际获得我的代码片段的功劳,而不是让其他人只是复制和粘贴他人代码的人声称这是他自己的。
这是我昨天做的功能。您输入用户和进程;然后它将遍历所有用户值(或本例中的计划)并检查它们中的任何一个是否包含在您包含的过程值数组中。基本上检查用户数组的任何值是否包含在流程需求数组的任何值中,这正是您想要的。
它将返回可用于 if
语句的真或假
<?php
define('PLAN_A',1); // 0001 <-- corrected
define('PLAN_B',2); // 0010
define('PLAN_C',4); // 0100
define('PLAN_D',8); // 1000
define('PLAN_E',16); // 10000
define('PLAN_F',32); // 10000
$user_one = array(PLAN_A,PLAN_C);
$user_two = array(PLAN_C);
$user_three = array(PLAN_F,PLAN_D);
$process_1 = array(PLAN_B);
$process_2 = array(PLAN_B,PLAN_D);
function check($user,$process){
foreach($user as $pl){
if(in_array($pl,$process)){
return true;
}
}
return false;
}
用法:
if(check($user_one,$process_1)){
echo 'true';
}else{
echo 'false';
}
现场演示:http://sandbox.onlinephpfunctions.com/code/83d8d135b03d584713738b56db40ecc21e9f4ddd