PhpRiot
Download This Article
Download this article or the entire “Implementing An N-Level Nested Tree In PHP And PostgreSQL” series with all listings and files.




More information
Related Books
Professional Linux Programming

Professional Linux Programming

As Linux increases its presence throughout the world as a target platform for professional...
Browse Articles
Ajax (4), APC (1), CAPTCHA (1), CSS (3), Debugging (1), File Upload (1), Google (3), Google Maps (2), JavaScript (12), JSON (2), MVC (1), MySQL (7), onbeforeunload (1), OOP (1), PHP (28), PhpDoc (1), PostgreSQL (6), Prototype (11), Reflection (1), RFC 1867 (1), Robots (1), Scriptaculous (1), SEO (1), Sessions (1), SimpleXML (1), Smarty (5), SOAP (1), SPL (1), Templates (2), W3C (1), XHTML (1), Zend Framework (1), Zend_Search_Lucene (1)

PhpRiot Newsletter
Your Email Address:

Implementing An N-Level Nested Tree In PHP And PostgreSQL, Part 1

Node Data Stored

We can represent this tree using just 3 pieces of information about each node:

  • A unique identifier (ID) for each node
  • Its title (e.g. General Resources)
  • The ID of its parent node (e.g. for the Links node, this would be the ID of General Resources)

Why the parent model is good

If we represent the tree using only the three items of information above, we can easily determine the following about a node:

  • We know it’s parent ID
  • The node’s siblings are all the other nodes with the same parent ID
  • The node’s children are all the nodes with a parent ID of the node’s ID.

Why the parent model is bad

Using only the ID, title and parent ID, it’s hard to determine anything other than siblings or children. For example, it would be hard to find every item within a single section, or to find the path from the root node to a node say 5 levels deep.

By hard, it can still be done, but will either require an arbitrary number of SQL statements, or require reading in the entire tree and processing it recursively.

In This Article


Tagged in , ,