從資料庫讀取巢狀資料(如目錄結構),輸出類似 Windows 檔案總管的樹狀列表。
<?php
// 資料表結構範例:
// dirent_types(id, icon, name)
// directory(id, parent, name, icon, type, url)
function icon($icon, $name = '', $w = 0, $h = 0) {
global $DOCUMENT_ROOT;
$file = "$DOCUMENT_ROOT/pics/menu/$icon.gif";
if (!$w || !$h) { $info = getimagesize($file); $w = $info[0]; $h = $info[1]; }
printf('<img%s border=0 align=top src="/pics/menu/%s.gif" width="%d" height="%d">',
$name ? " name=\"$name\"" : '', $icon, $w, $h);
}
function display_directory($parent, $showdepth = 0, $ancestors = false) {
global $child_nodes, $node_data, $last_child;
reset($child_nodes[$parent]);
$size = sizeof($child_nodes[$parent]);
$lastindex = $size - 1;
if (!$ancestors) $ancestors = array();
$depth = sizeof($ancestors);
printf('<div id="node_%d" class="dirEntry" visibility="%s">', $parent, $showdepth > 0 ? 'show' : 'hide');
while (list($index, $node) = each($child_nodes[$parent])) {
// 輸出縮排連線圖示
for ($i = 0; $i < $depth; $i++) {
$up = (int)$node_data[$ancestors[$i]]['parent'];
$last = $last_child[$up];
$uptree = $ancestors[$i];
icon($last == $uptree ? "blank" : "line");
}
$expand = !empty($child_nodes[$node]);
$conn = $expand ? "plus" : "join";
if ($index == $lastindex) $conn .= "bottom";
elseif ($depth == 0 && $index == 0) $conn .= "top";
if ($expand) printf("<a href=\"javascript:document.layers['node_%d'].visibility='show'\">", $node);
icon($conn, "connImg_$node");
if ($expand) print("</a>");
$icon = $node_data[$node]['icon'] ?: $GLOBALS['dirent_icons'][$node_data[$node]['type']];
icon($icon, "nodeImg_$node");
printf('<font size="%d">%s</font><br>', -1, $node_data[$node]['name']);
if ($child_nodes[$node]) {
$newdepth = $showdepth ? $showdepth - 1 : 0;
$new_ancestors = $ancestors; $new_ancestors[] = $node;
display_directory($node, $newdepth, $new_ancestors);
}
}
print("</div>");
}
function setup_directory($parent, $maxdepth) {
global $dirent_icons, $child_nodes, $node_data, $last_child;
$dirent_icons = sql_assoc('SELECT id,icon FROM dirent_types');
$res = sql('SELECT id,parent,type,icon,name FROM directory ORDER BY parent,name');
while (list($id,$parent,$type,$icon,$name) = db_fetch_row($res)) {
$child_nodes[(int)$parent][] = $id;
$node_data[$id] = compact('id','parent','type','icon','name');
$last_child[(int)$parent] = $id;
}
}
?>
需搭配資料庫連線函式 sql()、sql_assoc()、db_fetch_row()。