获取具有完整路径的类别列表

Get list of categories with full path

目前我得到了一个显示类别列表的代码。我能够创建一个子类别,但我想将其设置为无限,例如 category/sub-category/sub-sub-category/etc/article。类别数据库的结构是 id, title, slug parent_id 默认情况下是 0.

我试过循环查询,但有点不知道如何以正确的方式进行,就是没有用。

函数如下:

    public static function getCategoryList()
    {

        $db = Db::getConnection();

        $lang = self::Language();

        $categoryList = [];

        $result = $db->query("SELECT content.id, content.title$lang,content.slug$lang, content.sub_category_id, category.slug$lang FROM blog_category AS content LEFT JOIN blog_category AS category ON content.sub_category_id = category.id WHERE content.status='1' ORDER BY content.sort_order ASC");

        foreach($result as $row){
            $categoryList[] = [
                'id' => $row[0],
                'title' => $row[1],
                'slug' => $row[2],
                'sub_category' => $row[4],
            ];
        }
        return $categoryList;

    }

在HTML中:

    <?php foreach ($category as $categoryItem): ?>
        <h4><a href="/blog/<?php if ($categoryItem['sub_category']) echo $categoryItem['sub_category'] . '/'; ?><?php echo $categoryItem['slug']; ?>"><?php echo $categoryItem['title']; ?></a></h4>
        <p><?php echo $categoryItem['id']; ?></p>
    <?php endforeach; ?>

有很多不同的方法可以做到这一点,但我认为最好的方法是首先从数据库中将所有类别加载到 PHP,只要没有成千上万的类别。

$result = $db->query("SELECT category.id, category.parent_id, category.slug$lang FROM category");

// Populate $categories as an array of id => (slug, id, parent_id) items.

然后使用递归 php 函数构建类别面包屑。

function getBreadcrumb($categories, $categoryId) {

    $thisCat = $categories[$categoryId];

    if ($thisCat['parent_id'] != 0)
    {
       return array_merge(getBreadcrumb($categories, $thisCat['parent_id']), array($thisCat['slug']));
    }   
    else
    {
       return array($thisCat['slug']);
    }
}