I have this table:
+-------------------------------+
| NodeID | Parent | HasChildren |
+-------------------------------+
|1000000 |-1 |-1 |
+--------+--------+-------------+
|2409999 |1000000 |-1 |
+-------------------------------+
|2510921 |1000000 |-1 |
+-------------------------------+
|2596822 |2510921 |0 |
+-------------------------------+
|3000143 |2409999 |0 |
+-------------------------------+
|3125674 |2409999 |0 |
................................
the list goes on
… from which I need to build a html tree list using <ul> and <li>. Every node in this table is a child of top node with id 1000000 (which has Parent “-1”). Also, HasChildren “-1” tells that this node has children, 0 – it has not. Yes, it’s kinda weird convention, but it’s as it is. So, the output should be like this:
<ul>
<li>2409999</li>
<ul>
<li>3000143</li>
<li>3125674</li>
</ul>
<li>2510921</li>
<ul>
<li>2596822</li>
</ul>
....
</ul>
Perhaps someone has tackled the very same problem? Any help would be appreciated. Thanks!
As mentioned above, it would make sense to use a nested set representation in your table. If you decide to keep the existing table structure, then the general way of doing it is to have a recursive function along the lines of:
Needless to say the code above is pseudo-code, but it should demonstrate the general idea. The function executes on a single node, and if that node has children it calls itself on each of the children. That is called recursion. As a common programming convention: nodes that have children are called branches, and the ones that don’t are called leafs.