I am trying to get my data which is hierarchically set up with a tree traversal model into an < ul> in order to show on my site.
Here is my code:
Better Render Tree Function that worked for me (php function to prepare html source for use in jsTree jQuery plugin) instead of the Henrik Opel's one:
function MyRenderTree ( $tree = array(array('name'=>'','depth'=>'')) ){
$current_depth = 0;
$counter = 0;
$result = '<ul>';
foreach($tree as $node){
$node_depth = $node['depth'];
$node_name = $node['name'];
$node_id = $node['category_id'];
if($node_depth == $current_depth){
if($counter > 0) $result .= '</li>';
}
elseif($node_depth > $current_depth){
$result .= '<ul>';
$current_depth = $current_depth + ($node_depth - $current_depth);
}
elseif($node_depth < $current_depth){
$result .= str_repeat('</li></ul>',$current_depth - $node_depth).'</li>';
$current_depth = $current_depth - ($current_depth - $node_depth);
}
$result .= '<li id="c'.$node_id.'"';
$result .= $node_depth < 2 ?' class="open"':'';
$result .= '><a href="#"><ins> </ins>'.$node_name.'</a>';
++$counter;
}
$result .= str_repeat('</li></ul>',$node_depth).'</li>';
$result .= '</ul>';
return $result;}
Result HTML:
<ul>
<li id="c1" class="open"><a href="#"><ins> </ins>ELECTRONICS</a>
<ul>
<li id="c2" class="open"><a href="#"><ins> </ins>TELEVISIONS</a>
<ul>
<li id="c3"><a href="#"><ins> </ins>TUBE</a></li>
<li id="c4"><a href="#"><ins> </ins>LCD</a></li>
<li id="c5"><a href="#"><ins> </ins>PLASMA</a>
<ul>
<li id="c14"><a href="#"><ins> </ins>PLASMA1</a></li>
<li id="c15"><a href="#"><ins> </ins>PLASMA2</a></li>
</ul>
</li>
</ul>
</li>
<li id="c6" class="open"><a href="#"><ins> </ins>PORTABLE ELECTRONICS</a>
<ul>
<li id="c7"><a href="#"><ins> </ins>MP3 PLAYERS</a>
<ul>
<li id="c8"><a href="#"><ins> </ins>FLASH</a></li>
</ul>
</li>
<li id="c9"><a href="#"><ins> </ins>CD PLAYERS</a></li>
<li id="c10"><a href="#"><ins> </ins>2 WAY RADIOS</a></li>
</ul>
</li>
</ul>
</li>
</ul>