我想从一维数组构建层次结构,并且(几乎)可以使用或多或少的硬编码代码。如何使代码动态化?
也许是while(isset($array[$key])) { ... }
?
或者,有额外的功能?像这样:$out = my_extra_traverse_function($array,$key);
function array_traverse($array,$key=NULL) {
$out = (string) $key;
$out = $array[$key] . "/" . $out;
$key = $array[$key];
$out = $array[$key] ? $array[$key] . "/" . $out : "";
$key = $array[$key];
$out = $array[$key] ? $array[$key] . "/" . $out : "";
$key = $array[$key];
$out = $array[$key] ? $array[$key] . "/" . $out : "";
return $out;
}
$a = Array(102=>101, 103=>102, 105=>107, 109=>105, 111=>109, 104=>111);
echo array_traverse($a,104);
产出:107/105/109/111/104
答案 0 :(得分:2)
我认为你想要:
function array_traverse($array, $key = null) {
$out = (string) $key;
if (isset($array[$key])) {
$out = array_traverse($array, $array[$key]) . '/' . $out;
}
return $out;
}
或者,对于非递归方法:
function array_traverse($array, $key = null) {
$out = (string) $key;
while(isset($array[$key])) {
$out = $array[$key] . '/' . $out;
$key = $array[$key];
}
return $out;
}
答案 1 :(得分:1)
是的,我会说isset()
是要走的路:
traverse($array, $value) {
$result = array();
while (isset($array[$value])) {
array_unshift($result, $value);
# or just $result[] = $value if you want to append
# instead of prepending
$value = $array[$value];
}
return $result;
# or return implode('/', traverse(array(...))),
# but I always prefer array return types in such cases:
# they are much more flexible to the users of the function
}
# BTW: Using implode will avoid having an unnecessary
# leading/trailing delimiter (slash in this case)
echo implode('/', traverse(array(...)));