【发布时间】:2015-11-13 16:26:37
【问题描述】:
我正在尝试在嵌套的 PHP 数组中抓取并打印从根到叶的所有路径。例如,如果这是我的数组:
$tree = array(
"A" => "w",
"B" => array("x" => array("y", "z"))
)
我想要以下输出:
Array
(
[0] => Aw
[1] => Bxy
[2] => Bxz
)
这是我目前的功能:
function traverse($input, $myPath) {
global $allPaths;
if(is_array($input)) {
foreach($input as $k => $v) {
if(!is_int($k)) $myPath .= $k;
traverse($v, $myPath);
}
} else {
$myPath .= $input;
$allPaths[] = $myPath;
}
}
当我运行这段代码时:
$allPaths = array();
echo "<pre>";
traverse($tree, "");
print_r($allPaths);
echo "</pre>";
输出是这样的:
Array
(
[0] => Aw
[1] => ABxy
[2] => ABxz
)
这几乎是正确的,但由于某种原因,A 在到达“B”部分时被保留,而不是像我期望的那样被重置。
我反复阅读了代码并尝试了我能想到的所有调试消息,但仍然不明白发生了什么。我确定它要么是基本的东西(也许太多了,以至于如果我还没有看到它,我永远不会看到它)或者我只是不知道变量范围是如何在这里工作的。
【问题讨论】: