遍歷樹


由於某些事情上終於遇上無限分類的需要,所以就有了這篇筆記,這主要是記載一下相關的代碼片段,沒有詳細的用法.
主要就是結合了之前記下的類,相關連結 請按我前往

從資料庫中讀取資料部份

1
2
3
4
5
6
7
8
9
<?php
function getGroupTree() {
$query = $this->db->query("SELECT id, name, subject_or_group_id FROM ".$this->db_pre."xxxxxx ORDER BY id ASC");
while($row=$this->db->fetch_array($query)) {
$this->tree->setNode($row['id'], $row['parent_id'], $row['name']);
}
return $this->tree;
}
?>

建立整個結構用方法

1
2
3
4
5
6
<?php
// 調用剛才連結中的物件
require_once ROOT_PATH.'/class/tree.php';
// 這裡是我用到的設置方法,傳入初始化的樹給我寫的物件使用,再回傳出來
$groupTree = $adminUtil->setTree(new Tree())->getGroupTree();
?>

最後就是顯示

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<?php
showTree($subjectOrGroupTree);

// showTree(己生成的樹物件, 由樹的哪個位置開始, 目前所在樹的層數, 縮排的基數)
function showTree($tree, $startId = 0, $treeLevel = 1, $basePadding = 20) {
global $phpSelf, $sk;

// 計算縮排
$basePadding *= $treeLevel;

// 根據傳入的位置($startId)用迴圈遍歷整個子樹
foreach($tree->getChildsTree($startId) as $key => $id) {
echo '<tr class="t_body" onmouseover="this.className=\'t_body2\'" onmouseout="this.className=\'t_body\'">';
echo ' <td align="left" style="padding-left: '.$basePadding.'px">';
echo $tree->getValue($key);
echo ' </td>';
echo ' <td align="right">';
echo ' <a href="'.$phpSelf.'?sk='.$sk.'&op=addSubCategory&parentId='.$key.'">增加子類別</a>';
echo ' </td>';
echo '</tr>';

// 檢查是否還有目前子樹的子樹,如有則以迭代使用目前的函數
if (count($tree->getChild($key)) > 0) {
// 叫回自身,傳入整個樹物件,目前所在的子數鍵值,將層數累加
showTree($tree, $key, ++$treeLevel);
}
}
}
?>