Implementing An N-Level Nested Tree In PHP And PostgreSQL, Part 2
Article Comments (4 total)
goobernutz, 25 January 2010
Andrew Millne, 10 January 2010
Does this need updating to support PHP5? I'm having issues.
regan, 18 March 2009
Can Quentin confirm if the following will work to re-build the nleft + nright values etc starting at a particular node in the tree? (The $DB2 object is a connection to the database and particular to my code.)
/**
* Rebuilds the tree data from a particular node and saves it to the database
*/
function rebuildfromnode($id)
{
global $DB2;
$node = $this-getNode($id);
if (is_null($node))
return;
$data = $this-getTreeWithChildren();
// invoke the recursive function. Start it processing
// on the fake "root node" generated in getTreeWithChildren().
// because this node doesn't really exist in the database, we
// give it an initial nleft value of 0 and an nlevel of 0.
$idField = $this-fields['id'];
$this-_generateTreeData( $data, $node-$idField , $node-nlevel , $node-nleft );
// at this point the the root node will have nleft of 0, nlevel of 0
// and nright of (tree size * 2 + 1)
foreach ($data as $id = $row) {
// skip the root node
if ($id == 0)
continue;
$query = sprintf('update %s set nlevel = %d, nleft = %d, nright = %d where %s = %d',
$this-table,
$row-nlevel,
$row-nleft,
$row-nright,
$this-fields['id'],
$id);
$DB2-query($query);
}
}
Regan
Richard Wilson, 27 April 2008
Great article so far! Just a small bug. in the getPath method of the NestedTree class, the array iteration tries to access an empty property, $idField and causes a fatal error. This is because it has not been set. To fix, add $idField = $this-fields['id']; at the top of the method.
Cheers





The 5th anniversary of this article is rapidly approaching. How's part 3 coming along? :P