php id pid,关于无限分类的树状输出(id,name,pid)类型的数组
时间: 2023-08-03 12:06:31 浏览: 79
php无限分类树类方法
假设你有一个数组,其中包含了所有分类的信息,每个分类都有一个 ID、一个名称和一个父级分类的 ID。你可以使用递归函数来将这个数组转换成树状结构:
```php
function buildTree(array $items, $parentId = 0) {
$tree = [];
foreach ($items as $item) {
if ($item['pid'] == $parentId) {
$children = buildTree($items, $item['id']);
if ($children) {
$item['children'] = $children;
}
$tree[] = $item;
}
}
return $tree;
}
$categories = [
['id' => 1, 'name' => '分类1', 'pid' => 0],
['id' => 2, 'name' => '分类2', 'pid' => 0],
['id' => 3, 'name' => '分类3', 'pid' => 1],
['id' => 4, 'name' => '分类4', 'pid' => 1],
['id' => 5, 'name' => '分类5', 'pid' => 4],
['id' => 6, 'name' => '分类6', 'pid' => 2],
['id' => 7, 'name' => '分类7', 'pid' => 2],
];
$tree = buildTree($categories);
print_r($tree);
```
这个函数会递归遍历整个数组,以每个分类的父级 ID 作为参数进行调用。如果当前分类的父级 ID 匹配传入的父级 ID,那么就将当前分类加入到树状结构中,并递归调用函数来构建子树。最终,函数会返回根节点的数组,这个数组就是树状结构了。
输出结果:
```
Array
(
[0] => Array
(
[id] => 1
[name] => 分类1
[pid] => 0
[children] => Array
(
[0] => Array
(
[id] => 3
[name] => 分类3
[pid] => 1
[children] => Array
(
)
)
[1] => Array
(
[id] => 4
[name] => 分类4
[pid] => 1
[children] => Array
(
[0] => Array
(
[id] => 5
[name] => 分类5
[pid] => 4
[children] => Array
(
)
)
)
)
)
)
[1] => Array
(
[id] => 2
[name] => 分类2
[pid] => 0
[children] => Array
(
[0] => Array
(
[id] => 6
[name] => 分类6
[pid] => 2
[children] => Array
(
)
)
[1] => Array
(
[id] => 7
[name] => 分类7
[pid] => 2
[children] => Array
(
)
)
)
)
)
```
阅读全文