萬盛學電腦網

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

PHP 遞歸獲取分類樹所有子分類 ID 完整實作

核心遞歸函數

<?php
/**
 * 獲取指定父分類下所有子分類 ID (含孫輩)
 * @param array  $categories 分類陣列 [cid => ['cid'=>,'parent_cid'=>,'name'=>...]]
 * @param int    $parentId   父分類 ID,0 為頂級
 * @param bool   $includeSelf 是否包含父分類自身
 * @return array 所有子分類 ID 扁平陣列
 */
function getAllChildCategoryIds(array $categories, int $parentId = 0, bool $includeSelf = false): array
{
    $result = [];
    if ($includeSelf) {
        $result[] = $parentId;
    }

    foreach ($categories as $cat) {
        if (($cat['parent_cid'] ?? 0) === $parentId) {
            $result[] = $cat['cid'];
            // 遞歸獲取子分類
            $result = array_merge($result, getAllChildCategoryIds($categories, $cat['cid'], false));
        }
    }
    return $result;
}

// 使用範例
$cats = [
    1 => ['cid'=>1, 'parent_cid'=>0, 'name'=>'電子產品'],
    2 => ['cid'=>2, 'parent_cid'=>1, 'name'=>'手機'],
    3 => ['cid'=>3, 'parent_cid'=>2, 'name'=>'智能手機'],
    4 => ['cid'=>4, 'parent_cid'=>1, 'name'=>'電腦'],
    5 => ['cid'=>5, 'parent_cid'=>0, 'name'=>'服裝'],
];

$allMobileIds = getAllChildCategoryIds($cats, 1); // 獲取「電子產品」下所有子分類
// 結果: [2, 3, 4] (手機、智能手機、電腦)

優化版:靜態快取避免重複遍歷

<?php
class CategoryTree
{
    private array $categories;
    private array $childrenIndex = []; // parent_cid => [cid, ...]
    private array $cache = [];         // parentId => allChildIds

    public function __construct(array $categories)
    {
        $this->categories = $categories;
        $this->buildIndex();
    }

    private function buildIndex(): void
    {
        foreach ($this->categories as $cat) {
            $pid = $cat['parent_cid'] ?? 0;
            $this->childrenIndex[$pid][] = $cat['cid'];
        }
    }

    public function getAllChildIds(int $parentId, bool $includeSelf = false): array
    {
        if (isset($this->cache[$parentId])) {
            return $includeSelf 
                ? array_merge([$parentId], $this->cache[$parentId])
                : $this->cache[$parentId];
        }

        $ids = [];
        $this->collectChildren($parentId, $ids);
        $this->cache[$parentId] = $ids;

        return $includeSelf ? array_merge([$parentId], $ids) : $ids;
    }

    private function collectChildren(int $parentId, array &$ids): void
    {
        foreach ($this->childrenIndex[$parentId] ?? [] as $cid) {
            $ids[] = $cid;
            $this->collectChildren($cid, $ids);
        }
    }
}

// 使用
$tree = new CategoryTree($cats);
$ids = $tree->getAllChildIds(1); // [2, 3, 4]

資料庫層面優化:遞歸 CTE (MySQL 8.0+, PostgreSQL, SQL Server)

WITH RECURSIVE category_tree AS (
    SELECT cid, parent_cid, name, 0 AS level
    FROM item_cat_info
    WHERE cid = 1  -- 起始父分類
    
    UNION ALL
    
    SELECT c.cid, c.parent_cid, c.name, ct.level + 1
    FROM item_cat_info c
    INNER JOIN category_tree ct ON c.parent_cid = ct.cid
)
SELECT cid FROM category_tree WHERE cid != 1; -- 排除自身

單次查詢獲取完整子樹,無 N+1 問題,大數據量下效能碾壓 PHP 遞歸。

緩存策略:檔案/Redis 儲存樹結構

<?php
// 生成緩存檔案 (部署/後台更新時執行)
public function buildCacheFile(): void
{
    $db = Yii::app()->db;
    $list = $db->createCommand("SELECT cid, name, parent_cid, root_cid FROM item_cat_info")->queryAll();
    
    $categories = [];
    foreach ($list as $row) {
        $categories[$row['cid']] = $row;
    }
    
    $tree = new CategoryTree($categories);
    // 可選:預計算所有節點的子樹 ID 陣列
    $allSubTrees = [];
    foreach ($categories as $cid => $cat) {
        $allSubTrees[$cid] = $tree->getAllChildIds($cid);
    }
    
    $cacheData = [
        'categories' => $categories,
        'sub_trees'  => $allSubTrees,
        'updated_at' => time(),
    ];
    
    $file = Yii::getPathOfAlias('application.runtime') . '/category_tree.php';
    file_put_contents($file, '

前端樹形組件數據格式轉換

<?php
function buildTreeForVue(array $categories, int $parentId = 0): array
{
    $tree = [];
    foreach ($categories as $cat) {
        if (($cat['parent_cid'] ?? 0) === $parentId) {
            $node = [
                'id'    => $cat['cid'],
                'label' => $cat['name'],
                'children' => buildTreeForVue($categories, $cat['cid']),
            ];
            if (empty($node['children'])) unset($node['children']);
            $tree[] = $node;
        }
    }
    return $tree;
}
// 輸出 JSON 給 Element UI el-tree / Ant Design Tree / Vue-Treeselect 直接使用

總結選型

場景推薦方案
數據量小 (<1000)、簡單專案PHP 遞歸函數 + 靜態快取
數據量中等、頻繁查詢PHP 類封裝 + 檔案/Redis 緩存預計算子樹
數據量大 (>1萬)、多伺服器資料庫遞歸 CTE + Redis 緩存
需前端樹形選擇器PHP 遞歸構建巢狀 JSON 結構
copyright © 萬盛學電腦網 all rights reserved