Recurse properly

I have a few navigation-related features that I would like to have without depth restrictions. They generate CSS menus, breadcrumbs, etc.

I am focused on how I will make the functions by following each path to depth or root without an explicit loop.

Below is a typical example where I want to get the topmost parent of a page. The topmost value will have a value of 0 in the field parent

.

Here's an explicit loopback version:

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

      

Does anyone have any advice or similar code or link to tute to help point the way?

+1


a source to share


3 answers


It is easily expressed as a while loop:

$node = $this;
while ($node->parent != 0) {
  $node = $this->retrieve("id = '$node->parent'");
}

      



$node

now contains the top-most element.

+8


a source


Welbog's answer is the nicest one, but for completeness I'll add another recursive solution:



function topPg() {
   function foo($p) {
     $gp = $this->retrieve("id = '$p->parent'");
     return ($gp->parent == 0) ? $p : foo($gp);
   }  

   return foo($this);
}

      

+1


a source


I haven't tested it, but it should work ..:

function recurse( $pg )
{
    $parent_pg = $pg->retrieve( 'id = ' . $this->parent );

    if( $parent_pg->parent != 0 )
    {
        recurse( $parent_pg );
    }
    else
    {
        return $pg;
    }

}

      

0


a source







All Articles