PHP枚举层次结构

我想为我的
PHP应用程序创建分层Enumarations并想到类似的东西

abstract class User_Roles extends Enum {

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

}

我正在使用这个Enum-Class: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
  )
)

有什么我误解或忽视的吗?

最佳答案 你必须遍历$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) { } 
          } 
    } 
}
点赞