NYCPHP Meetup

NYPHP.org

[nycphp-talk] Managing Nested Sets in a Database

csnyder chsnyder at gmail.com
Wed Nov 16 11:41:35 EST 2005


On 11/15/05, Jeff Loiselle <jeff.loiselle at gmail.com> wrote:
> Hello,
>
> So I completely understand how to add nodes, removes nodes, move
> nodes, select children and parents. But I'm having a hard time
> figuring out how to draw trees in select boxes and using packages like
> PEAR::HTML_TreeMenu to build trees without using recursion. I'm going
> brain-dead on this one. The fcnyNode class has been extremely helpful
> along with the articles I'm reading which I posted before.
>
> What's my big hangup? ;-)
>
> /jeff

You can loop through all the nodes in a set (you'll need to sooner or
later, if only to display them) and use the parentId to keep track of
relative depth.

Or you can tie the tree to a conventional hierarchical naming system,
and count the nameparts of any node to determine its depth.

The first method looks something like the following, where $nodes is
an array of nodes.

$previous = FALSE;
foreach( $nodes AS $index=>$child ) {
  if ( !$previous ) {
    $depth = array( $child->parentId );
  }
  else {
    if ( $child->parentId == $previous->id ) {
      // child of previous
      $depth[] = $child->id;
    }
    else {
      $popped = array_pop( $depth );
      while ( $popped && $popped != $child->parentId ) {
        // close containers
        $popped = array_pop( $depth );
      }
      $depth[] = $child->parentId;
      if ( $child->parentId != $this->id ) {
        $depth[] = $child->id;
      }
    }
  }
  $nodes[$index]->depth = count( $depth );
  $previous = $child;
}

Following that, each node in the $nodes array will have a depth property.

--
Chris Snyder
http://chxo.com/


More information about the talk mailing list