正确递归

jer*_*iuh 1 php recursion

我有几个导航相关的功能,我希望没有深度限制.这些生成CSS菜单,痕迹痕迹等.

我很难过如何使函数遵循每条路径深度或根本没有显式循环.

以下是我想要页面最顶层父项的典型示例.最顶层的parent字段值为零.

这是显式循环版本:

function topPg() {
    $p = $this->retrieve("id = '$this->parent'");
    if ($p->parent != 0) {
        $gp = $this->retrieve("id = '$p->parent'");
        if ($gp->parent != 0) {
            $ggp = $this->retrieve("id = '$gp->parent'");
            if ($ggp->parent != 0) {
                $gggp = $this->retrieve("id = '$ggp->parent'");
                // ad naseum
            } else {
                return $ggp;
            }
        } else {
            return $gp;
        }
    } else {
        return $p;
    }
} // func
Run Code Online (Sandbox Code Playgroud)

任何人都有建议或类似的代码或tute链接帮助指明方向?

Wel*_*bog 8

它很容易表现为while循环:

$node = $this;
while ($node->parent != 0) {
  $node = $this->retrieve("id = '$node->parent'");
}
Run Code Online (Sandbox Code Playgroud)

$node 现在包含最顶层的元素.