無限分類(多級分類、樹狀結構)是電商分類、部門架構、選單系統的核心需求。本文提供遞歸與非遞歸兩種實作、資料庫設計、效能優化、前端渲染完整方案。
CREATE TABLE categories (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
pid INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '父級 ID,0 為頂層',
name VARCHAR(100) NOT NULL,
slug VARCHAR(100) NOT NULL,
sort INT UNSIGNED NOT NULL DEFAULT 0,
level TINYINT UNSIGNED NOT NULL DEFAULT 1 COMMENT '層級深度,冗余欄位加速查詢',
path VARCHAR(500) NOT NULL DEFAULT '' COMMENT '路徑:0/1/5/12,祖先鏈',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
INDEX idx_pid (pid),
INDEX idx_path (path)
);
<?php
$categories = [
['id' => 1, 'pid' => 0, 'name' => '電子產品', 'sort' => 1],
['id' => 2, 'pid' => 0, 'name' => '服飾鞋包', 'sort' => 2],
['id' => 3, 'pid' => 1, 'name' => '手機', 'sort' => 1],
['id' => 4, 'pid' => 1, 'name' => '筆電', 'sort' => 2],
['id' => 5, 'pid' => 3, 'name' => 'iPhone', 'sort' => 1],
['id' => 6, 'pid' => 3, 'name' => 'Android', 'sort' => 2],
['id' => 7, 'pid' => 5, 'name' => 'iPhone 15', 'sort' => 1],
['id' => 8, 'pid' => 2, 'name' => '男裝', 'sort' => 1],
['id' => 9, 'pid' => 8, 'name' => '襯衫', 'sort' => 1],
];
<?php
function buildTreeRecursive(array $items, int $pid = 0): array {
$tree = [];
foreach ($items as $item) {
if ($item['pid'] == $pid) {
$children = buildTreeRecursive($items, $item['id']);
if ($children) {
$item['children'] = $children;
}
$tree[] = $item;
}
}
return $tree;
}
$tree = buildTreeRecursive($categories);
echo json_encode($tree, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
<?php
function buildTreeLinear(array $items, int $rootPid = 0): array {
// 1. 建立 ID 索引(引用)
$refs = [];
foreach ($items as &$item) {
$item['children'] = []; // 預設空子陣列
$refs[$item['id']] = &$item; // 關鍵:引用賦值
}
unset($item); // 解除引用
// 2. 單次遍歷掛載
$tree = [];
foreach ($refs as $id => &$item) {
if ($item['pid'] == $rootPid) {
$tree[] = &$item; // 根節點
} elseif (isset($refs[$item['pid']])) {
$refs[$item['pid']]['children'][] = &$item; // 掛載到父節點
}
// 孤兒節點(pid 不存在)可選擇忽略或放入特殊容器
}
unset($item);
return $tree;
}
$tree = buildTreeLinear($categories);
// 效能:10萬筆資料 < 50ms vs 遞歸 > 5s
<?php
// MySQL 8.0+ 遞歸 CTE 查詢完整樹
$sql = "
WITH RECURSIVE category_tree AS (
-- 錨點:根節點
SELECT id, pid, name, 1 AS level, CAST(name AS CHAR(500)) AS path_name
FROM categories WHERE pid = 0
UNION ALL
-- 遞歸:子節點
SELECT c.id, c.pid, c.name, ct.level + 1, CONCAT(ct.path_name, ' > ', c.name)
FROM categories c
INNER JOIN category_tree ct ON c.pid = ct.id
)
SELECT * FROM category_tree ORDER BY path_name;
";
// PostgreSQL 同樣支援
// SQL Server: 使用 CTE
// Oracle: CONNECT BY PRIOR
<!-- CategoryTree.vue -->
<script setup>
defineProps({
nodes: { type: Array, required: true },
level: { type: Number, default: 0 }
});
const emit = defineEmits(['select']);
</script>
<template>
<ul class="tree-level-{{ level }}">
<li v-for="node in nodes" :key="node.id">
<div class="node" @click="emit('select', node)">
<span class="indent" :style="{ paddingLeft: level * 20 + 'px' }"></span>
<span v-if="node.children?.length" class="toggle">▼</span>
<span class="name">{{ node.name }}</span>
</div>
<CategoryTree v-if="node.children?.length" :nodes="node.children" :level="level + 1" @select="emit('select', $event)" />
</li>
</ul>
</template>
<?php
function renderTreeHtml(array $tree, int $level = 0): string {
$html = '';
foreach ($tree as $node) {
$html .= '- ';
$html .= '';
$html .= '';
if (!empty($node['children'])) {
$html .= '▼';
}
$html .= '' . htmlspecialchars($node['name']) . '';
$html .= '';
if (!empty($node['children'])) {
$html .= renderTreeHtml($node['children'], $level + 1);
}
$html .= '
';
}
$html .= '
';
return $html;
}
echo renderTreeHtml($tree);
<?php
function getNodePath(array $tree, int $targetId): array {
foreach ($tree as $node) {
if ($node['id'] == $targetId) {
return [['id' => $node['id'], 'name' => $node['name']]];
}
if (!empty($node['children'])) {
$subPath = getNodePath($node['children'], $targetId);
if ($subPath) {
array_unshift($subPath, ['id' => $node['id'], 'name' => $node['name']]);
return $subPath;
}
}
}
return [];
}
// 使用 path 欄位(資料庫冗余)O(1) 取得路徑
// SELECT * FROM categories WHERE id = 7 → path = '0/1/3/5/7'
// 解析 path 取得所有祖先 ID,一次查詢取回
<?php
function moveNode(PDO $pdo, int $nodeId, int $newPid): bool {
// 1. 檢查不形成循環:新父節點不能是自己或後代
$descendants = getAllDescendantIds($pdo, $nodeId);
if (in_array($newPid, $descendants) || $nodeId == $newPid) {
throw new Exception('不能移動到自己或子孫節點下');
}
// 2. 計算層級差異
$stmt = $pdo->prepare("SELECT level, path FROM categories WHERE id = ?");
$stmt->execute([$nodeId]);
$node = $stmt->fetch();
$stmt->execute([$newPid]);
$newParent = $stmt->fetch();
$levelDiff = ($newParent['level'] + 1) - $node['level'];
$newPath = $newParent['path'] . '/' . $nodeId;
$pathPrefixLen = strlen($node['path']) + 1; // 包含分隔符
// 3. 事務更新:自身 + 所有後代
$pdo->beginTransaction();
try {
// 更新自身
$pdo->prepare("UPDATE categories SET pid = ?, level = level + ?, path = ? WHERE id = ?")
->execute([$newPid, $levelDiff, $newPath, $nodeId]);
// 更新後代 path(MySQL 8.0+ 可用 CTE 批次更新,舊版需分批)
$pdo->prepare("UPDATE categories SET path = CONCAT(?, SUBSTRING(path, ?)), level = level + ?
WHERE path LIKE ?")
->execute([$newPath, $pathPrefixLen, $levelDiff, $node['path'] . '/%']);
$pdo->commit();
return true;
} catch (Exception $e) {
$pdo->rollBack();
throw $e;
}
}
| 策略 | 適用場景 | 實現 |
|---|---|---|
| Closure Table | 頻繁查詢祖先/後代、移動子樹 | 額外表存儲所有祖先後代關係 (ancestor, descendant, depth) |
| Nested Set (左/右值) | 讀多寫少、需快速取得子樹 | lft/rgt 值編碼樹結構,移動節點成本高 |
| Path Enumeration (路徑) | 讀寫均衡、需麵包屑、MySQL 5.7+ | path='0/1/5/12',LIKE '0/1/5/%' 查子樹 |
| 遞歸 CTE | MySQL 8.0+/PG、臨時查詢 | WITH RECURSIVE 動態查詬,無冗余欄位 |
| 快取樹結構 | 極少變更、高讀取 | Redis 存儲完整 JSON 樹,變更時重建 |