在php开发中,我们经常从数据库取出形如 id、parent_id 的扁平数据,需要把它们按父子关系整理成嵌套数组,同时希望控制最多递归几层,防止层级太深影响性能或前端展示。

一、准备扁平数据
假设从数据库查出的数据是一个普通数组,每条记录有 id 和 parent_id,parent_id 为 0 表示顶级。
<?php
// 模拟数据库查出的扁平数据
$list = array(
array('id' => 1, 'parent_id' => 0, 'name' => '服装'),
array('id' => 2, 'parent_id' => 1, 'name' => '男装'),
array('id' => 3, 'parent_id' => 1, 'name' => '女装'),
array('id' => 4, 'parent_id' => 2, 'name' => '衬衫'),
array('id' => 5, 'parent_id' => 0, 'name' => '数码'),
);
?>
二、递归生成嵌套数组
利用引用把子节点挂到父节点的 children 键上,同时通过深度参数限制递归层数。
<?php
function buildTree($list, $parentId = 0, $depth = 1, $maxDepth = 3) {
$tree = array();
if ($depth > $maxDepth) {
return $tree;
}
foreach ($list as &$item) {
if ($item['parent_id'] == $parentId) {
$children = buildTree($list, $item['id'], $depth + 1, $maxDepth);
if (!empty($children)) {
$item['children'] = $children;
}
$tree[] = $item;
}
}
return $tree;
}
$result = buildTree($list, 0, 1, 3);
print_r($result);
?>
代码要点说明
- 函数 buildTree 接收扁平数组、当前父id、当前深度和最大深度。
- 使用 & 引用遍历,让挂接 children 时直接修改原数据。
- 当 depth 超过 maxDepth 时直接返回空,实现层级深度控制。
三、如果不限制深度的写法
若不需要控制层级,可去掉深度参数,递归直到没有子节点:
<?php
function buildTreeNoLimit($list, $parentId = 0) {
$tree = array();
foreach ($list as &$item) {
if ($item['parent_id'] == $parentId) {
$children = buildTreeNoLimit($list, $item['id']);
if (!empty($children)) {
$item['children'] = $children;
}
$tree[] = $item;
}
}
return $tree;
}
?>
四、总结
按父子 id 生成嵌套数组的核心是利用递归和引用。加上深度参数就能轻松控制层级,避免无限嵌套。实际项目中建议把最大深度做成可配置项,方便不同业务场景复用同一套 php 数据整理逻辑。
php递归nested_arrayparent_child_id修改时间:2026-07-27 06:03:18