php将一个包含父子关系的扁平化数组转换成树形菜单
发表于:2023-05-18 12:31:49浏览:2125次
以下是将一个包含父子关系的扁平化数组转换成树形菜单的PHP递归函数示例:
function generateTree($flatArray, $parentId = null) {
$tree = [];
foreach ($flatArray as $item) {
if ($item['parent_id'] === $parentId) {
$node = [
'id' => $item['id'],
'name' => $item['name'],
'children' => generateTree($flatArray, $item['id'])
];
$tree[] = $node;
}
}
return $tree;
}
该函数接受一个包含父子关系的扁平化数组和可选的parentId参数作为输入。它会遍历数组并找到所有具有指定父ID的节点,将它们转换为对象,并在children属性中递归调用它自己以获取每个节点的子节点。最终,它将返回一个树形菜单对象数组。
例如,假设我们有以下扁平化数组:
$flatArray = [
['id' => 1, 'parent_id' => null, 'name' => 'Home'],
['id' => 2, 'parent_id' => 1, 'name' => 'About'],
['id' => 3, 'parent_id' => 1, 'name' => 'Contact'],
['id' => 4, 'parent_id' => 2, 'name' => 'History'],
['id' => 5, 'parent_id' => 2, 'name' => 'Team'],
['id' => 6, 'parent_id' => 3, 'name' => 'Support'],
['id' => 7, 'parent_id' => 3, 'name' => 'Sales']
];
我们可以调用generateTree($flatArray,0)以获取以下树形菜单对象数组:
[
[
'id' => 1,
'name' => 'Home',
'children' => [
[
'id' => 2,
'name' => 'About',
'children' => [
['id' => 4, 'name' => 'History', 'children' => []],
['id' => 5, 'name' => 'Team', 'children' => []]
]
],
[
'id' => 3,
'name' => 'Contact',
'children' => [
['id' => 6, 'name' => 'Support', 'children' => []],
['id' => 7, 'name' => 'Sales', 'children' => []]
]
]
]
]
]
推荐文章
- ES6新特性总结
- 开源免费的企业办公系统,勾股OA2.0发布
- 字符编码Unicode新增五个新的行星符号
- 云服务器挂载云盘,以天翼云为例子的挂载步骤
- 使用搜狐IP地址查询接口获取IP所在城市
- thinkphp6 leftjoin联表查询时,子表有多条记录去重后获取子表的最新记录查询方法
- 利用微软的Office Online实现Office文档在线预览功能
- PHP8.5将于2025年11月20日正式发布,还在用PHP 5.6的老版本用户该何去何从?
- CSS 选择器::is(), :where(), 和:has()伪元素的运用
- ThinkPHP6判断HTTP的请求类型是GET,POST,PUT,DELETE或者HEAD

