[nycphp-talk] Managing Nested Sets in a Database
Cliff Hirsch
cliff at pinestream.com
Wed Nov 16 13:03:37 EST 2005
I calculate the depth when adding/updating/deleting nodes and store the
depth in the database. If the set is read intensive, this reduces the
processing load. For a simple indent, I use this:
<div style="margin-left: {$category_list->category[i].level-1}em">
-----Original Message-----
From: talk-bounces at lists.nyphp.org [mailto:talk-bounces at lists.nyphp.org]
On Behalf Of csnyder
Sent: Wednesday, November 16, 2005 11:42 AM
To: NYPHP Talk
Subject: Re: [nycphp-talk] Managing Nested Sets in a Database
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/ _______________________________________________
New York PHP Talk Mailing List
AMP Technology
Supporting Apache, MySQL and PHP
http://lists.nyphp.org/mailman/listinfo/talk
http://www.nyphp.org
More information about the talk
mailing list