CodeIgniter实现多级分类必须单次查库再PHP递归组装:表中parent_id设为NULL,查询用get()一次性获取全部数据,build_tree()函数须传引用并严格判空(=== null),视图层用递归函数渲染,加深度防护防栈溢出。

多级分类数据必须一次性查出,不能递归查库
CodeIgniter 没有内置树形查询能力,get_where() 或 join() 都无法自动展开无限级父子关系。常见错误是:在循环里对每个 parent_id 单独查一次数据库——这会立刻触发 N+1 查询,页面加载变慢甚至超时。
正确做法是用单次查询拉取全部分类记录,再用 PHP 组织结构:
- 表结构中必须有
id、parent_id(顶级设为NULL,不是0)、name、slug等基础字段 - 查询语句写成
$this->db->order_by('sort', 'asc')->get('categories')->result_array(),不加where条件 - 避免在 Model 中调用
$this->db->get_where('categories', ['parent_id' => $id])这类带条件的多次查询
build_tree() 函数必须传引用,且判空要严格
PHP 递归组装树时,如果函数参数没加 &$tree,子节点永远写不进上级数组——这是最常被忽略的 bug。同时,parent_id === null 和 parent_id == 0 在 PHP 中行为不同,数据库存的是 NULL,代码里就必须用全等判断。
一个最小可用的递归函数骨架:
private function build_tree($items, $parent_id = null, &$tree = []) {
foreach ($items as $item) {
if ($item['parent_id'] === $parent_id) {
$item['children'] = [];
$tree[] = $item;
$this->build_tree($items, $item['id'], $tree[count($tree)-1]['children']);
}
}
return $tree;
}
- 入口调用写成
$menu_tree = $this->build_tree($all_categories);,别漏掉&$tree引用声明 - 加深度防护:在函数开头加
static $depth = 0; if (++$depth > 10) return;,防栈溢出 - 不要在视图层做递归渲染逻辑,把完整树结构一次性传给 View
导航模板要支持嵌套,但避免硬编码层级
View 层用纯 PHP 递归渲染比写多层 foreach 更可靠。硬编码三层 foreach(一级→二级→三级)看似简单,但遇到四级分类就崩,也不利于后续维护。
推荐在视图中定义一个局部递归函数(CI 允许在 View 中写函数):
<?php
function render_menu($items) {
if (empty($items)) return;
echo '<ul>';
foreach ($items as $item) {
echo '<li><a href="' . base_url($item['slug']) . '">' . htmlspecialchars($item['name']) . '</a>';
if (!empty($item['children'])) {
render_menu($item['children']);
}
echo '</li>';
}
echo '</ul>';
}
render_menu($menu_tree);
?>
- 每次递归前检查
!empty($item['children']),防止 Notice 错误 -
htmlspecialchars()必须包裹输出内容,防 XSS - 不要在
<li>外层再套<div>或其它容器——CSS 控制层级更灵活
active 状态不能靠 URI 段匹配,得靠路由或显式标记
很多人用 $this->uri->segment(1) 对比菜单 slug 来标亮当前项,但一旦用了路由重写(比如 $route['products'] = 'catalog/list';),segment(1) 是 products,而控制器实际是 catalog,状态就错乱了。
更稳的方式是在控制器里手动设置 active 字段:
- 在构建
$menu_tree前,先拿到当前路由名:$current_controller = $this->router->class;或$this->router->method; - 遍历菜单数组时,比对
$item['controller'] === $current_controller,匹配则设$item['active'] = true - 或者更粗暴但有效:在控制器方法顶部直接写
$data['active_slug'] = 'products';,View 中用它比对
复杂点在于,多级菜单的“激活”可能需要向上追溯父级也高亮——这得在递归函数里加一层回溯逻辑,而不是只标叶子节点。


















