Spage Cat, Prince Among Thieves RSS Feed

Simple Single Pass Doubly Linked Flat Tree Building Algorithm

A hierarchy is a common structure, especially in web development.  The problem with hierarchies is they need to be flattened to be stored in a relational database, and then expanded again after being pulled out. 

An Example Hierarchy
  • Top level item
    • Sub Item
      • Sub Sub Item
        • Sub Sub Sub Item
    • Sibling of Sub Item
  • Top level as well

 

A common and simple way to store them is with a table structure similar to the following.

id

parent_id

title

1

0

Top level item

2

0

Top level as well

3

1

Sub Item

4

1

Sibling of Sub Item

5

3

Sub Sub Item

6

6

Sub Sub Sub Item

Now there are several ways to return this to a multidimensional array or other navigable structure. A painfully common and naïve way would be recursive queries ala:

function fetch_items($parent = 0) {
	$data = array();
	$qry = mysql_query("select * from `tablename`  where parent_id = " . (int)$parent );
	while( $row = mysql_fetch_array($qry) ) {
		$data = array('data' => $row, 'children' => fetch_items($row['id']));
	}
	return $data;
}
  

The problem with this approach is the sheer number of queries this approach uses. Our simple example hierarchy would execute 6 queries, whereas more complicated hierarchies would execute many more.

A better approach is to pull all the data out with a single query, and then process it into the structure we need.  There are several ways to do this, but I find the following DOM like structure this generates incredibly useful.

function fetch_tree() {
	$data = array();
	$qrt  = mysql_query("select * from `tablename` order by parent_id asc");
	while( $row = mysql_fetch_array($qry) ) {
		$data[ $row['id'] ]['data'] = $row;
		$data[ $row['parent_id'] ]['children'][ $row['id'] ] =& $data[ $row['id'] ];
  		$data[ $row['id'] ]['parent'] =& $data[ $row['parent_id'] ];
 	}
	return $data;
}
  

Essentially, in a single pass through the data, this gets us an array of hierarchy elements, where rather than an element directly having its children, every entry has a pointer to its parent element as well as an array of pointers to its children. This is incredibly flexible, and as the tree is flattened it allows you to start at any point in the hierarchy by ID ala $data[id], and navigate your way up or down. Viewing any elements children is as simple as $data[id][ 'children'], and its parent as simple as $data[id]['parent'].

I use this basic methodology a ton in my work, personal and professional (the comments and sitemap of this site are powered by it!) but the concept seems foreign when I try to explain it to people.  I hope this explanation sparks some ideas for people.


Read More / Comment »

Nusphere PhpED Dark Theme

It would seem there is a fair deal of call for an updated version of my PhpED dark theme from colleagues as well as random folks on the internet who’ve seen screenshots of my PhpED installation. I previously had my Dark Theme for 5 linked on my Review of PhpED, but I figured I could have a page d…
Read More / Comment »

301 RewriteRule Generator

I find myself often needing to set up a large number of 301 redirects from an excel file of old to new url’s. Until this point, writing these had been a fairly exhausting process as you need to be certain to escape every character that could be picked up by the regular expression engine, or risk u…
Read More / Comment »

Last.fm donatJ

The Hold Steady - Stay Positive
Oren Lavie - The Opposite SIde Of The Sea
Owen - At Home With Owen
Gorillaz - D-Sides: Remixes [Disc 2]
Panic at the Disco - Live In Chicago
Ólafur Arnalds - ...and they have escaped the weight of darkness
Halloween, Alaska - Champagne Downtown
AWOLNATION - Megalithic Symphony
Andrew Bird - Andrew Bird & the Mysterious Production of Eggs

Flickr donatJ

STP81610
STP81609
STP81608
STP81607
STP81606
STP81605
STP81603
STP81602

Twitter @donatJ

Really enjoyed the portion on Bisect though a lot of it flew a bit over my head. I've always wanted to know more about it!
Link

Rebasing is for losers. Trees FTW
Link

A Brief, Incomplete, and Mostly Wrong History of Programming Languages
Link

This light sprinkling of snow does *not* justify 10mph on 494.
Link

Well here I was hoping Facebook and Google would be down today and I might actually get something done. Sigh
Link

I'm taking Design and Analysis of Algorithms I online for free. Come join me!
Link

Recent Comments

When I attempt to navigate to the script (saved as a .txt) in terminal I get the message "Permission denied"...I am the only account on my macbook and the admin…
Link

Just wanted to say thanks for this. I am a complete novice and manage to follow these instructions. You legend!!!
Link

Great work, retrieved my 13 year old daughter's Photo Booth library dating back to 2006 :) All the best from Kris, Melbourne, Australia.
Link

Just wanted to say thanx. Saves my eyes.
Link

1. If W3C deprecated elements like <font> you should not use them by simple facts. Though they are supported in current browsers in order to ensure backwa…
Link

Tag Cloud