现在好像无限级别分类比较火,现在LZ使用PHP引用实现无限级分类,
算法复杂度为T(n)=O(2n),只遍历两次数组.
给各位TPer提供一种新的无限级分类思路
关键代码其实只有一行
$return[$v['pid']]['child'][$v['id']] = &$return[$k];
但是为了实现较为复杂的扩展,这里添加一些额外的信息
//索引要和ID一致,这不是废话么
//pid是父元素
//不要出现死循环嵌套,就是AB互为父子
//不要出现相同name
$list[0]=['id'=>0,'pid'=>-1,'name'=>'A@0'];//-1用于后面的根目录判断
$list[1]=['id'=>1,'pid'=>0,'name'=>'A@1'];
$list[2]=['id'=>2,'pid'=>0,'name'=>'A@2'];
$list[3]=['id'=>3,'pid'=>2,'name'=>'A@3'];
$list[4]=['id'=>4,'pid'=>3,'name'=>'A@4'];
$list[5]=['id'=>5,'pid'=>0,'name'=>'A@5'];
$list[6]=['id'=>6,'pid'=>1,'name'=>'A@6'];
//先初始化目录
$return=[];
foreach($list as $v)
$return[$v['name']]=[];
//将每个目录与父目录进行拼接,并找到根目录
foreach($list as $k=>$v)
{
if($v['pid']>=0)
$return[$list[$v['pid']]['name']][$v['name']]=&$return[$v['name']];
else
$parent=$v['name'];
}
//打印根目录
print_r($return[$parent]);
Array
(
[A@1] => Array
(
[A@6] => Array
(
)
)
[A@2] => Array
(
[A@3] => Array
(
[A@4] => Array
(
)
)
)
[A@5] => Array
(
)
)
/**
* Created by PhpStorm.
* User: Nikaidou-Shinku
* Date: 16/9/14
* Time: 17:12
*/
$list[] = ['id' => 0, 'pid' => -1, 'name' => 'A@0'];//-1用于后面的根目录判断
$list[] = ['id' => 1, 'pid' => 0, 'name' => 'A@1'];
$list[] = ['id' => 2, 'pid' => 0, 'name' => 'A@2'];
$list[] = ['id' => 3, 'pid' => 2, 'name' => 'A@3'];
$list[] = ['id' => 4, 'pid' => 3, 'name' => 'A@4'];
$list[] = ['id' => 5, 'pid' => 0, 'name' => 'A@5'];
$list[] = ['id' => 6, 'pid' => 1, 'name' => 'A@6'];
//先初始化目录
$return = [];
$parent = '';
foreach ($list as $v)
$return[$v['id']] = [
'id' => $v['id'],
'name' => $v['name'],
'pid' => $v['pid'],
'child' => '',
];
//将每个目录与父目录进行拼接,并找到根目录
foreach ($return as $k => $v) {
if ($v['pid'] >= 0)
$return[$v['pid']]['child'][$v['id']] = &$return[$k];
else
$parent = &$return[$k];
}
//打印根目录
var_export($parent);
$aa=[
'id' => 0,
'name' => 'A@0',
'pid' => -1,
'child' =>
[
1 =>
[
'id' => 1,
'name' => 'A@1',
'pid' => 0,
'child' =>
[
6 =>
[
'id' => 6,
'name' => 'A@6',
'pid' => 1,
'child' => '',
],
],
],
2 =>
[
'id' => 2,
'name' => 'A@2',
'pid' => 0,
'child' =>
[
3 =>
[
'id' => 3,
'name' => 'A@3',
'pid' => 2,
'child' =>
[
4 =>
[
'id' => 4,
'name' => 'A@4',
'pid' => 3,
'child' => '',
],
],
],
],
],
5 =>
[
'id' => 5,
'name' => 'A@5',
'pid' => 0,
'child' => '',
],
],
]