使用php递归构建一个Category树

时间:2014-02-20 01:37:38

标签: php mysql recursion tree

我有一个MySQL表,其类别如下:

categoryID | categoryName  | parentID
------------------------------------
1          | books         | NULL
------------------------------------
2          | newspapers    | NULL
------------------------------------
3          | sci-fi        | 1
------------------------------------
4          | robot stories | 3
-------------------------------------
etc.

当我只有“机器人故事”的ID时,我需要用递归建立一个类别树。它必须看起来像:

书籍 - >科幻 - >机器人故事

任何建议都会有所帮助!

1 个答案:

答案 0 :(得分:0)

如果树不是太大,我会把整个东西加载到内存中(你也可以缓存它):

$tree = [];
$stmt = $db->query("SELECT * FROM categories");
while (($row = $stmt->fetch(PDO::FETCH_ASSOC)) !== false) {
    $tree[$row['categoryID']] = $row;
}

$currentCategoryId = 4;
$hierarchy = [];

// build hierarchy, working from leaf to root
while (isset($tree[$currentCategoryId])) {
    array_unshift($hierarchy, $tree[$currentCategoryId]);
    $currentCategoryId = $tree[$currentCategoryId]['parentId'];
}

print_r($hierarchy);