无限极分类:一次查询建树
不用递归查数据库,一次取出全部分类,在内存里用引用建树,输出层级结构。
更新于 2026-11-1338 行代码
完整代码
PHP
<?php
function build_tree(array $rows, int $rootId = 0): array
{
$map = [];
foreach ($rows as $row) {
$row['children'] = [];
$map[$row['id']] = $row;
}
$tree = [];
foreach ($map as $id => &$node) {
$pid = (int)$node['parent_id'];
if ($pid === $rootId) {
$tree[] = &$node;
} elseif (isset($map[$pid])) {
$map[$pid]['children'][] = &$node;
}
}
unset($node);
return $tree;
}
function tree_options(array $tree, int $depth = 0): array
{
$out = [];
foreach ($tree as $node) {
$out[] = [
'id' => $node['id'],
'name' => str_repeat(' ', $depth) . ($depth > 0 ? '└ ' : '') . $node['name'],
'depth' => $depth,
];
if ($node['children']) {
$out = array_merge($out, tree_options($node['children'], $depth + 1));
}
}
return $out;
}
怎么用
- $rows = $pdo->query('SELECT id, parent_id, name FROM categories ORDER BY sort ASC')->fetchAll();
- $tree = build_tree($rows); 得到嵌套数组,直接给模板递归渲染。
- 下拉框用 tree_options($tree),会带上缩进和连接符。
注意
- 引用建树的关键是 &$node 和最后 unset($node),漏掉 unset 会导致最后一个节点被重复写入。
- 父级被删除或形成环时,节点会从树上消失,建树前最好校验 parent_id 是否存在。
- 分类层级超过五层时,考虑改成路径字段(path = 0,1,5),查询子树更方便。