简体   繁体   中英

Build a Category tree with a php recursion

I have a MySQL table with categories whic look like:

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

I need to build a category tree with recursion when I have only the ID of 'robot stories' and it has to look like:

books -> sci-fi -> robot stories

Any advise will be helpful!

If the tree is not too big, I would just load the whole thing in memory (you can cache it too):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM