php分类导航实现
实现PHP分类导航的方法
数据库设计
创建分类表存储分类信息,通常包含字段如id、name、parent_id、sort_order等。示例SQL:
CREATE TABLE categories (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
parent_id INT DEFAULT 0,
sort_order INT DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
递归获取分类树
使用递归函数获取多级分类结构:
function getCategoryTree($parent_id = 0) {
$categories = [];
$query = "SELECT * FROM categories WHERE parent_id = $parent_id ORDER BY sort_order";
$result = mysqli_query($connection, $query);
while ($row = mysqli_fetch_assoc($result)) {
$row['children'] = getCategoryTree($row['id']);
$categories[] = $row;
}
return $categories;
}
渲染导航菜单
将分类树渲染为HTML导航菜单:
function renderMenu($categories, $level = 0) {
$html = '<ul class="nav-level-' . $level . '">';
foreach ($categories as $category) {
$html .= '<li>';
$html .= '<a href="/category/' . $category['id'] . '">' . $category['name'] . '</a>';
if (!empty($category['children'])) {
$html .= renderMenu($category['children'], $level + 1);
}
$html .= '</li>';
}
$html .= '</ul>';
return $html;
}
缓存优化
对分类数据进行缓存减少数据库查询:
function getCachedCategories() {
$cache_key = 'category_tree';
$cache_time = 3600; // 1小时
if ($cached = apc_fetch($cache_key)) {
return $cached;
}
$categories = getCategoryTree();
apc_store($cache_key, $categories, $cache_time);
return $categories;
}
前端样式处理
为多级菜单添加CSS样式:

.nav-level-0 { background: #f8f9fa; }
.nav-level-1 { background: #e9ecef; margin-left: 15px; }
.nav-level-2 { background: #dee2e6; margin-left: 30px; }
无限级分类优化
对于大量分类数据,考虑使用闭包表(Closure Table)或嵌套集(Nested Set)模型替代简单的父ID方案,提高查询效率。






