PHP Enum Hierarchy
我想为我的PHP应用程序创建分层枚举,并考虑如下事项
1 2 3 4 5 6 7 8 | abstract class User_Roles extends Enum { const Administrator =""; const Account_Manager ="Administrator"; const BlogAuthor ="Account_Manager"; const CommentManager ="Account_Manager"; } |
我正在使用这个枚举类:所以
所以每个子节点都有它的父节点作为值。
我就是这样做的:
1 2 3 4 5 6 7 8 | $constants = $reflector->getConstants(); foreach ($constants as $key => $value) { if ($value =="") { $returnHierarchy[$key] = array(); continue; } $returnHierarchy[][$value] = $key; } |
但我想创建的多维数组有一些问题。
所以应该是这样的:
1 2 3 4 5 6 7 8 | [Administrator] { [Account_Manager] { [BlogAuthor] [CommentManager] } } |
但我最终会遇到这样的事情:
1 2 3 4 5 6 7 8 9 10 11 12 |
有什么我误解或忽视的吗?
如果您的
要在数组中搜索,必须使用递归函数,该函数将返回匹配的子数组索引引用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | // 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; } |
然后简单地使用上面定义的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | $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); |
1 2 3 4 5 6 7 8 |