萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 遞歸實現無限分類樹狀結構完整範例

無限分類(多級分類、樹狀結構)是電商分類、部門架構、選單系統的核心需求。本文提供遞歸與非遞歸兩種實作、資料庫設計、效能優化、前端渲染完整方案。

資料庫設計

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);

方法二:引用陣列單次遍歷建樹(O(N) 效能、大數據首選)

<?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

方法三:資料庫層級遞歸查詢(CTE,MySQL 8.0+、PostgreSQL)

<?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

前端渲染:遞歸元件

Vue 3 範例

<!-- 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>

原生 JS 遞歸渲染

<?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/%' 查子樹
遞歸 CTEMySQL 8.0+/PG、臨時查詢WITH RECURSIVE 動態查詬,無冗余欄位
快取樹結構極少變更、高讀取Redis 存儲完整 JSON 樹,變更時重建

總結選擇指南

  • < 1 萬筆、簡單展示:PHP 端 `buildTreeLinear()` 即可
  • 頻繁查詢祖先/後代、需移動節點:資料庫 `path` 欄位 + 索引,或 Closure Table
  • MySQL 8.0+ / PostgreSQL:優先使用 CTE 遞歸查詢,簡潔無冗余
  • 前端大樹渲染:虛擬滾動、懶加載子節點、搜尋過濾
copyright © 萬盛學電腦網 all rights reserved