Forum Moderators: coopster

Message Too Old, No Replies

Building Hierarchical Tree

From parent child table

         

ukgimp

2:58 pm on Sep 16, 2003 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hello

Is it difficult to build a hierarchical tree from a table that has a parent field. Imagine that the table was:

Cat ¦ Parent
1¦ null
2¦1
3¦1
4¦3
5¦3
6¦1

is it difficult to get the following:

1
--2
--3
----4
----5
--6

If possible does anyone know of and good examples of this online so I can learn from it.

Cheers

jpjones

3:05 pm on Sep 16, 2003 (gmt 0)

10+ Year Member



I'm looking into doing this myself over the next couple of days. A quick google for "php hierarchical tree" brings up a few resources. Number 1 result at DevShed looks like it'll help you to do what you want.

JP

ukgimp

3:36 pm on Sep 16, 2003 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Cheers jp

I was looking through devshed and found a recursive query, but there was a commemt whic hmade me think twice

this is not an efficient algorithm
* because it has to issue one query per category!

That worries me :)

There has to be a slick way of doing it.

magicke

4:09 pm on Sep 16, 2003 (gmt 0)

10+ Year Member



hmm...

Slicker would be to incorporate each record's heirarchy level in a system-assigned id field (if thats not in your table definition yet).

You could then do an str_repeat("-", <heirarchylevel>) in the resultset display loop, like so...

while (!eof) {
echo str_repeat("&nbsp;", sqlresultset->fields("hLevelID"));
echo sqlresultset->fields("AcctID")."<br>\n";
}

It'd cost you a few bytes per record, but does allow you to do the formatting with a single query.

magicke

dmorison

4:21 pm on Sep 16, 2003 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



How big is your tree going to be?

If not too big just read the table in one go and do whatever you want with the array in memory.