## PHP迭代与递归实现无限级分类

| |
[ 所属分类 开发（php） | 发布者 店小二03 | 时间 | 作者 红领巾 ] 0人收藏点击收藏

1.循环迭代实现

\$arr = [
1=>['id'=>1,'name'=>'父1','father'=>NULL],
2=>['id'=>2,'name'=>'父2','father'=>NULL],
3=>['id'=>3,'name'=>'父3','father'=>NULL],
4=>['id'=>4,'name'=>'儿1-1','father'=>1],
5=>['id'=>5,'name'=>'儿1-2','father'=>1],
6=>['id'=>6,'name'=>'儿1-3','father'=>1],
7=>['id'=>7,'name'=>'儿2-1','father'=>2],
8=>['id'=>8,'name'=>'儿2-1','father'=>2],
9=>['id'=>9,'name'=>'儿3-1','father'=>3],
10=>['id'=>10,'name'=>'儿3-1-1','father'=>9],
11=>['id'=>11,'name'=>'儿1-1-1','father'=>4],
12=>['id'=>12,'name'=>'儿2-1-1','father'=>7],
];
function generateTree(\$items){
\$tree = array();
foreach(\$items as \$item){
if(isset(\$items[\$item['father']])){
\$items[\$item['father']]['son'][] = &\$items[\$item['id']];
}else{
\$tree[] = &\$items[\$item['id']];
}
}
return \$tree;
}
\$tree = generateTree(\$arr);
print_r(json_encode(\$tree));

2.递归实现

\$arr = [
0=>['id'=>1,'name'=>'父1','father'=>0],
1=>['id'=>2,'name'=>'父2','father'=>0],
2=>['id'=>3,'name'=>'父3','father'=>0],
3=>['id'=>4,'name'=>'儿1-1','father'=>1],
4=>['id'=>5,'name'=>'儿1-2','father'=>1],
5=>['id'=>6,'name'=>'儿1-3','father'=>1],
6=>['id'=>7,'name'=>'儿2-1','father'=>2],
7=>['id'=>8,'name'=>'儿2-1','father'=>2],
8=>['id'=>9,'name'=>'儿3-1','father'=>3],
9=>['id'=>10,'name'=>'儿3-1-1','father'=>9],
10=>['id'=>11,'name'=>'儿1-1-1','father'=>4],
11=>['id'=>12,'name'=>'儿2-1-1','father'=>7],
];
function generateTree(\$arr,\$id,\$step){
static \$tree=[];
foreach(\$arr as \$key=>\$val) {
if(\$val['father'] == \$id) {
\$flg = str_repeat('└D',\$step);
\$val['name'] = \$flg.\$val['name'];
\$tree[] = \$val;
generateTree(\$arr , \$val['id'] ,\$step+1);
}
}
return \$tree;
}
\$tree = generateTree(\$arr,0,0);
foreach (\$tree as \$val){
echo \$val['name'].'<br>';
}

输出:

tags: gt,id,father,name,tree,val,arr,items,generateTree,迭代,key,NULL

1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责；
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性，不作出任何保证或承若；
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。