我想为我的PHP应用程序创建分层Enumarations并想到像
这样的东西 “Recording… Press Ctrl+C to Stop.”
ALSA lib pcm_hw.c:1667:(_snd_pcm_hw_open) Invalid value for card
arecord: main:722: audio open error: No such file or directory
“Processing…”
我正在使用此枚举类:SO
因此每个孩子都有他的父节点作为它的价值。
这就是我要这样做的方式:
abstract class User_Roles extends Enum {
const Administrator = "";
const Account_Manager = "Administrator";
const BlogAuthor = "Account_Manager";
const CommentManager = "Account_Manager";
}
但是我想要创建的多维数组存在一些问题。
所以看起来应该是这样的:
$constants = $reflector->getConstants();
foreach ($constants as $key => $value) {
if ($value == "") {
$returnHierarchy[$key] = array();
continue;
}
$returnHierarchy[][$value] = $key;
}
但我最终会这样:
[Administrator]
{
[Account_Manager]
{
[BlogAuthor]
[CommentManager]
}
}
有什么我误解或忽视的吗?
答案 0 :(得分: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) { }
}
}
}