PHP实现无限级分类

时间:2022-05-27 12:23:12

前段时间做一个小项目的时候用到了无限级分类,当时也忘的差不多了,于是就去网上查资料学,下面是我的学习笔记

数据格式:

array (size=5)
1 =>
array (size=6)
'id' => string '1' (length=1)
'pid' => string '0' (length=1)
'name' => string '青年之声1' (length=13)
'description' => string '' (length=0)
'create_time' => string '2017-04-02 15:38:06' (length=19)
'del' => string '0' (length=1)
2 =>
array (size=6)
'id' => string '2' (length=1)
'pid' => string '1' (length=1)
'name' => string '青年之声2' (length=13)
'description' => string '' (length=0)
'create_time' => string '2017-04-02 15:38:06' (length=19)
'del' => string '0' (length=1)
3 =>
array (size=6)
'id' => string '3' (length=1)
'pid' => string '2' (length=1)
'name' => string '青年之声3' (length=13)
'description' => string '' (length=0)
'create_time' => string '2017-04-02 15:38:06' (length=19)
'del' => string '0' (length=1)
4 =>
array (size=6)
'id' => string '4' (length=1)
'pid' => string '3' (length=1)
'name' => string '青年之声4' (length=13)
'description' => string '' (length=0)
'create_time' => string '2017-04-02 15:38:06' (length=19)
'del' => string '0' (length=1)
5 =>
array (size=6)
'id' => string '5' (length=1)
'pid' => string '4' (length=1)
'name' => string '青年之声5' (length=13)
'description' => string '' (length=0)
'create_time' => string '2017-04-02 15:38:06' (length=19)
'del' => string '0' (length=1)

非递归算法

$tree = array();
foreach ($items as $item) {
if (isset($items[$item['pid']])) {
$items[$item['pid']]['childs'][] = &$items[$item['id']];
} else {
$tree[] = &$items[$item['id']];
}
}

递归算法

function getChild($id) {
$tree = [];
$childs = Columns::find()->where(['pid' => $id, 'del' => 0])->asArray()->all();
if ($childs) {
foreach ($childs as $child) {
$childTree = getChild($child['id']);
if ($childTree) {
$child['children'] = $childTree;
}
$tree[] = $child;
}
}
return $tree;
}

最终结果

PHP实现无限级分类