2016-02-14 88 views
4

我要創建我的PHP應用程序和對事物的思想層次Enumarations像PHP枚舉層次

abstract class User_Roles extends Enum { 

    const Administrator = ""; 
    const Account_Manager = "Administrator"; 
    const BlogAuthor = "Account_Manager"; 
    const CommentManager = "Account_Manager"; 

} 

我使用這個枚舉級:SO

所以每個孩子都有自己的父節點爲這是價值。

這是我會怎麼做:

$constants = $reflector->getConstants(); 
    foreach ($constants as $key => $value) { 
     if ($value == "") { 
      $returnHierarchy[$key] = array(); 
      continue; 
     } 
     $returnHierarchy[][$value] = $key; 
    } 

但我有我要創建多維數組的一些問題。

因此,它應該是這樣的:

[Administrator] 
{ 
    [Account_Manager] 
    { 
     [BlogAuthor] 
     [CommentManager] 
    } 
} 

但我結束了這樣的東西:

array(4) (
    [Administrator] => array(0) 
    [0] => array(1) (
    [Administrator] => (string) Account_Manager 
) 
    [1] => array(1) (
    [Account_Manager] => (string) BlogAuthor 
) 
    [2] => array(1) (
    [Account_Manager] => (string) CommentManager 
) 
) 

有什麼,我誤解或忽視?

回答

1

你必須遍歷$contstants和內部搜索您$returnHierarchy如果您$value的角色已經有追加,如果沒有創造新的

要在數組搜索,你必須使用這將返回匹配的子數組索引參考

遞歸函數
// IMPORTANT: it return reference function mae mast start with & 
function &searchKeyInArray($key, &$array){ 

     $matchedArrayReffarance = null; 

     if(!isset($array[$key])){ 

      foreach ($array as &$sub){ 

       if(is_array($sub)){ 
        $matchedArrayReffarance = &searchKeyInArray($key, $sub); 
       } 
      } 
     }else{ 
      $matchedArrayReffarance = &$array; 
     } 

     return $matchedArrayReffarance; 
} 

那麼簡單的使用定義searchKeyInArray上面就可以實現你在找什麼

$returnHierarchy = array(); 
// This is example, in your case it is: $constants = $reflector->getConstants(); 
$constants = array(
     'Administrator' => "", 
     'Account_Manager' => "Administrator", 
     'BlogAuthor' => "Account_Manager", 
     'CommentManager' => "Account_Manager", 
); 

foreach ($constants as $key => $value) { 

    $matchArray = &searchKeyInArray($value, $returnHierarchy); 

    if(isset($matchArray)){ 
     $matchArray[$value][$key] = array(); 
    }else{ 
     $returnHierarchy[$key] = array(); 
    } 
} 

var_dump($returnHierarchy); 

$returnHierarchy後續代碼var_dump將

array(1) { 
    ["Administrator"]=> &array(1) { 
      ["Account_Manager"]=> array(2) { 
       ["BlogAuthor"]=> array(0) { } 
       ["CommentManager"]=> array(0) { } 
      } 
    } 
} 
+0

阿爾緬您好,謝謝您的回答。但是,您可以添加運行時獲得的輸出嗎?當我運行它,然後我得到幾乎相同的輸出如問題所示。將不勝感激:) – Snickbrack

+0

嗨還好我更新了答案 – Armen

+0

謝謝,現在它像一個魅力:) – Snickbrack