(可能很简单)条件PHP循环


(Probably Simple) Conditional PHP Loop

我设置了一个数据库表,如下所示:

table: group
id     name          subGroupOf
1      grandparent   NULL
2      parent           1
3      child            2

以下是我在php中尝试做的事情:

当用户访问一个页面时,页面会告诉auth()函数他们需要"child"权限。因为"child"是"parent"的子组,所以两个组的成员都应该获得权限。但是,parent是"祖父母"的一个子组,因此所有三个组的成员都应该有访问权限。

由于嵌套的子组数量没有限制,所以我知道我需要一个循环。但我完全是一片空白。

我知道它需要检查组是否是subGroupOf,如果是,则验证父组。到目前为止,我拥有的是:

        // Get group of current user
        $group = mysqli_query($cxn,'SELECT group FROM user WHERE id='.$userID);
        // Compare group to permissions
        if($group == $permissions)
            return TRUE;
        // Check if group is a sub group
        $subGroupOf = mysqli_query($cxn,'SELECT subGroupOf FROM group WHERE id="'.$group.'"');
        if($subGroupOf == NULL)
        {
            // Wrong permissions
        }
        // Check if the parent group matches permissions
        if($subGroupOf == $permissions)
            return TRUE;

不知怎么的,我需要循环最后一部分,当它到达时停止

$subGroupOf == NULL

我对编程还很陌生,所以我还在弄清楚逻辑。。。有什么想法吗?我不需要为我写所有的东西(无论如何,代码都是总结的),我只需要帮助弄清楚结构。。

另一种方法,但您仍然需要一个递归函数:

  1. 创建一个函数,将组的层次结构添加到数组中
  2. 循环浏览组的数组,并检查您的权限

功能

function getGroupHierarchy($groupId, $cxn)
{
    $groupArray = array();
    //Push the group to the array..
    $groupArray[] = $groupId;
    //Get the parent id of this group
    $subGroupOf = mysqli_query($cxn,'SELECT subGroupOf FROM group WHERE id="'.$groupId.'"');
    //There is no parent, just return the array.
    if($subGroupOf == NULL)
    {
        return $groupArray;
    }
    //Continue checking the parent group(s).
    getGroupHierarchy($subGroupOf, $cxn);
}

调用函数并检查权限:

// Get group of current user
$groupId = mysqli_query($cxn,'SELECT group FROM user WHERE id='.$userID);
$allGroups = getGroupHierarchy($groupId, $cxn);
//Compare each group to permissions.
foreach($groupArray as $group)
{
    if($group == $permissions)
        return TRUE;
}

您可以通过一个递归函数来执行此操作,该函数检查子组,并一直持续到"subGroupOf"id为NULL。

例如:

function getTopParentGroup($groupId, $cxn) {
    $subGroupOf = mysqli_query($cxn,'SELECT subGroupOf FROM group WHERE id="'.$groupId.'"');
    //There is no parent, just return the group
    if($subGroupOf == NULL)
    {
        return $group;
    }
    //A parent has been found, continue...  
    getTopParentGroup($subGroupOf, $cxn);
}