Re: How do I make a HTML tree for a set of nodes?

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Hi!

On Sunday 04 June 2006 18:13, Martin Alterisio wrote:
[snip]

> I had a similar problem that, although it was with a binary tree, it can
> be used with your tree. PHP doesn't like too much the use of recursion,
> but this time recursion is the way to go (if you want to keep the code
> maintainable). Hopefully the tree will not span deep enough to cause any
> problems... (hopefully).
> 
> The function will receive a node and return a table representation of the
> branch started by this tree, if you point this function to the root node
> you'll have your table. In each cell it will have to indicate whether it
> is empty, it has a node or a line connecting neighbor cells. One important
> thing to define here is the way the function will organize the nodes in
> the table, in my function the root node was at the top in the center.
> 
> First, the trivial case: if the node doesn't have children return a table
> with one cell, the node itself.
> Then, the recursive case: if the node have children, call the function
> with those nodes and store the tables returned. According to the
> representation I used, it calculated the combined width of those tables,
> created a new table where the first row contained the parent node
> centered, the second line an horizontal line from the column where the
> first children would be to the column where the last children would be.
> Then it build the rest of the table pasting together, horizontally, the
> tables of the children. Voila! a nice table representation of the tree.

This sounds fine -- recursion is obviously the way to go. Where can I see
your function?

I tried several different solutions over the last couple of hours, and I've
settled on only using indentation (like a nested <ul></ul> list), not a
fancy graph with antialised branches. It's the simplest possible recursion
but I like the results, even if it's a bit harder to grasp without
connections clearly marked.


function tree($nodes, $start, $indent=-30) {
        $indent+=30;
        global $tree;
        foreach ($nodes as $nodeID => $node) {
                if ($node['parent']!=$start) {continue;}
                $tree.="<div style='margin-left:{$indent}px'>{$node['name']}</div>";
                tree($nodes, $nodeID, $indent);
        }
        return $tree;
}



Thanks!

//Niels

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux