select * from tree where lft between 2 and 11 order by lft asc; 剩下的问题如何显示层级的缩进了。
<?php function display_tree($root) { // 得到根节点的左右值 $result = mysql_query('select lft, rgt from tree '.'where name="'.$root.'";'); $row = mysql_fetch_array($result);
// 准备一个空的右值堆栈 $right = array();
// 获得根基点的所有子孙节点 $result = mysql_query('select name, lft, rgt from tree '. 'where lft between '.$row['lft'].' and '. $row['rgt'].' order by lft asc;');
// 显示每一行 while ($row = mysql_fetch_array($result)) { // only check stack if there is one if (count($right)>0) { // 检查我们是否应该将节点移出堆栈 while ($right[count($right)-1]<$row['rgt']) { array_pop($right); } }
<?php function rebuild_tree($parent, $left) { // the right value of this node is the left value + 1 $right = $left+1;
// get all children of this node $result = mysql_query('select name from tree '. 'where parent="'.$parent.'";'); while ($row = mysql_fetch_array($result)) { // recursive execution of this function for each // child of this node // $right is the current right value, which is // incremented by the rebuild_tree function $right = rebuild_tree($row['name'], $right); }
// we've got the left value, and now that we've processed // the children of this node we also know the right value mysql_query('update tree set lft='.$left.', rgt='. $right.' where name="'.$parent.'";');
// return the right value of this node + 1 return $right+1; } ?> 当然这个函数是一个递归函数,我们需要从根节点开始运行这个函数来重建一个带有左右值的树