<?php
// 原始数组
$originalArray = [
0 => ["id" => 1, "parent_id" => 0, "name" => "首页", "name_id" => "1"],
1 => ["id" => 2, "parent_id" => 0, "name" => "用户管理", "name_id" => "2"],
2 => ["id" => 3, "parent_id" => 2, "name" => "商品管理", "name_id" => "2-3"],
3 => ["id" => 4, "parent_id" => 2, "name" => "余额管理", "name_id" => "2-4"]
];
// 递归函数,用于构建树状结构
function buildTree($array, $parentId = 0) {
$tree = [];
foreach ($array as $item) {
if ($item['parent_id'] == $parentId) {
$children = buildTree($array, $item['id']);
if ($children) {
$item['children'] = $children;
}
$tree[] = $item;
}
}
return $tree;
}
// 调用递归函数构建树状结构
$tree = buildTree($originalArray);
// 打印树状结构
print_r($tree);
?>
运行上述代码将输出以下结果:
Array
(
[0] => Array
(
[id] => 1
[parent_id] => 0
[name] => 首页
[name_id] => 1
)
[1] => Array
(
[id] => 2
[parent_id] => 0
[name] => 用户管理
[name_id] => 2
[children] => Array
(
[0] => Array
(
[id] => 3
[parent_id] => 2
[name] => 余额管理
[name_id] => 2-3
)
[1] => Array
(
[id] => 4
[parent_id] => 2
[name] => 商品管理
[name_id] => 2-4
)
)
)
)
?
这样,你就成功地将原始数组转换成了树状结构。每个节点都有一个唯一的id
,以及指向其父节点的parent_id
。如果一个节点有子节点,它还将包含一个children
数组。