PHP 枚举层次结构

PHP Enum Hierarchy

我想为我的 PHP 应用程序创建分层枚举,并想到了

abstract class User_Roles extends Enum {

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

}

我正在使用这个 Enum-Class:SO

所以每个 child 都有他的 parent 节点值。

我会这样做:

    $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
  )
)

有没有我误解或忽略的地方?

如果你的 $value 角色已经存在,你必须循环 $contstants 并在你的 $returnHierarchy 中搜索 如果没有则创建新角色

要在数组中搜索,您必须使用递归函数,它将 return 匹配子数组索引引用

// 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) { } 
          } 
    } 
}