目前我有一个显示类别列表的代码。我能够制作一个单独的子类别,但我想让它无限像类别/子类别/子子类别/ 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(getBreatcrumb($thisCat['parent_id']), array($thisCat['slug']));
}
else
{
return array($thisCat['slug']);
}
}