2012-09-12 67 views
0

我已經建立了一個數據庫表像這樣:(可能是簡單的)條件PHP循環

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

這裏就是我想要在PHP做:

當用戶訪問一個頁面,該頁面告訴auth()函數他們需要'子'權限。因爲「孩子」是「父」的子組,所以兩個組的成員都應該獲得權限。但是,父母是「祖父母」的一個子羣體,所以三個羣體的成員都應該有權訪問。

由於沒有限制,有多少亞組可以被嵌套,我知道我需要一個循環。但我完全畫空白。

我知道它需要檢查組是一個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 

我是相當新的節目,所以我還在盤算走出邏輯......任何想法?我不需要爲我寫的所有東西(代碼總結總之),我只需要幫助搞清楚結構。

+0

澄清。假設用戶組是「小孩」。因此,你想讓實際的組加載爲「祖父母」,因爲「孩子」是「父母」的子組,「父母」是「祖父母」的子組? – Axel

+0

不確定你的意思是「加載」。我希望腳本將用戶的組以及該組的任何父組與組之間進行比較,並將其與該組需要的頁面進行比較。 – user1564018

回答

0

另一種方法,但你仍然需要遞歸函數:

  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; 
} 
0

你可以通過一個遞歸函數來檢查子組,並繼續直到「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); 
} 
+0

我知道我很小氣,但是如何在不使用某個功能的情況下執行此操作?也許有一個While循環? – user1564018

+0

我不認爲這是可能的。你說組的數量沒有限制,因此每次都必須連續循環返回不同的變量值。你將不得不做某種遞歸函數來遍歷每個組並檢索它的父項。 – Axel