【问题标题】:Check if any item in one array is contained in any item in another array检查一个数组中的任何项是否包含在另一个数组中的任何项中
【发布时间】:2021-05-15 20:33:09
【问题描述】:

我有一系列订阅/计划(访问级别):

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 ?或者,如何检查用户数组的任何值是否包含在流程需求数组的任何值中?

【问题讨论】:

标签: php arrays privileges


【解决方案1】:

由于其中一位用户 (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

【讨论】:

  • 感谢您提供完整的答案 - 并将“检查”过程作为一项功能 - 使其非常容易适应我的应用程序。沙盒中的示例很有帮助,因为它让我可以轻松地测试其他组合。我一整天都在为此苦苦挣扎,试图让按位工作,但您的解决方案非常出色,可以按需要工作。
  • @RickHellewell 不客气 bud :) 我很高兴能帮上忙!而且我可能应该首先将其作为答案发布,而不是对您的问题发表评论,所以这是我的错,您可能会早点看到它:L
  • 由于时区(和睡眠),很快就看到了。下一个问题是存储和检索用户访问角色 - 将用户权限放入 $user_x 数组。正在研究。
  • 也许将它作为 json 存储在某个地方?
  • 目前正在尝试将数组序列化/通用化为表中的中等 blob。似乎工作。我想我可以 json 它,但这似乎工作正常。
【解决方案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 .

【讨论】:

    猜你喜欢
    • 2011-01-16
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 2022-01-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多