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; } ?> 當然這個函數是一個遞歸函數,我們需要從根節點開始運行這個函數來重建一個帶有左右值的樹