【发布时间】:2011-12-05 11:06:30
【问题描述】:
基于Getting a modified preorder tree traversal model (nested set) into a <ul>
其中一个答案给出了正确的代码来显示完整的树。我需要的是始终显示活动列表项的第一级(深度=0)和兄弟姐妹+孩子。目标是当用户选择更多列表项的父列表项时扩展树的可见部分。
所以,如果我得到这个列表:
1. item
2. item
2.1. item
2.2. item
2.2.1. item
2.2.2. item
2.2.3. item
2.3. item
2.4. item
2.4.1. item
2.4.2. item
3. item
4. item
4.1. item
4.2. item
4.2.1. item
4.2.2. item
5. item
如果当前列表项为“2.”,则列表应如下所示:
1. item
2. item // this needs class .selected
2.1. item
2.2. item
2.3. item
2.4. item
3. item
4. item
5. item
如果当前列表项是“2.2.”,则列表应如下所示:
1. item
2. item // this needs class .selected
2.1. item
2.2. item // this needs class .selected
2.2.1. item
2.2.2. item
2.2.3. item
2.3. item
2.4. item
3. item
4. item
5. item
下面有一个示例代码,可以很好地显示完整的树。我还添加了 lft/rgt/current 来解决我的问题。
<?php
function MyRenderTree ( $tree = array(array('name'=>'','depth'=>'', 'lft'=>'','rgt'=>'')) , $current=false){
$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="#">'.$node_name.'</a>';
++$counter;
}
$result .= str_repeat('</li></ul>',$node_depth).'</li>';
$result .= '</ul>';
return $result;
}
// "$current" may contain category_id, lft, rgt for active list item
print MyRenderTree($categories,$current);
?>
【问题讨论】:
-
你的意思是“$current”可能包含活动列表项的category_id、lft、rgt?它是一个包含 3 个数据的数组吗?
-
@satrun77 它是一个包含“选定”列表项值的数组。
标签: php html arrays traversal nested-sets