select * from tree where lft between 2 and 11 order by lft asc; 剩下的問題如何顯示層級(jí)的縮進(jìn)了。
<?php function display_tree($root) { // 得到根節(jié)點(diǎn)的左右值 $result = mysql_query('select lft, rgt from tree '.'where name="'.$root.'";'); $row = mysql_fetch_array($result);
// 準(zhǔn)備一個(gè)空的右值堆棧 $right = array();
// 獲得根基點(diǎn)的所有子孫節(jié)點(diǎn) $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) { // 檢查我們是否應(yīng)該將節(jié)點(diǎn)移出堆棧 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; } ?> 當(dāng)然這個(gè)函數(shù)是一個(gè)遞歸函數(shù),我們需要從根節(jié)點(diǎn)開始運(yùn)行這個(gè)函數(shù)來重建一個(gè)帶有左右值的樹