Constructing a tree with recursion

From: Date: Mon, 06 May 2002 08:17:46 +0000
Subject: Constructing a tree with recursion
Groups: php.general 
Request: Send a blank email to php-general+get-96212@lists.php.net to get a copy of this message
Hi all, ok, here is my problem. I have a table in my db which is like this: id name parent_id 1 menu1 0 2 menu2 0 3 menu3 0 4 menu4 0 5 sub1 1 6 sub2 2 7 sub3 3 8 sub4 6 9 sub5 7 10 sub6 9 which would be a tree like this (well, not actually a tree, more like a couple of linear linear lists starting from a point where parent_id == 0): menu1 -> sub1 menu2 -> sub2 -> sub4 menu3 -> sub3 -> sub5 -> sub6 menu4 or something like this :) The table always has less than 200 rows, so I just go right ahead an read all values into my array $categories. So now everything is let's say in: $categories['id'] $categories['name'] and $categories['parent_id'] I now make my $tree array and push every array from categories on it if it meets $categories['parent_id'] == 0 to start with for ($i=0; $i < count($categories); $i++) { if ($categories['parent_id'] == 0) $tree[] = $categories[$i]; } Now comes the hard part where help would be appreciated. How do I recursively run through $categories and add all the subs to the right $tree? If you have any ideas I would be very glad. Sasa Velickovic http://www.hexatex.de PS: I don't look for a nested sets algo to recursively select the right datasets from the database ...

« previous php.general (#96212) next »