php 分类树,php 无限级分类树

php无限级tree,用迭代和递归方式实现php递归实现无限级分类树。树状列表常常用户分类、节点、菜单和导航等等。

迭代:函数内某段代码实现循环

递归:重复调用函数自身实现循环

第一:迭代(效率高)function list_to_tree($list){

$list = array_column($list, null, 'id');

foreach ($list as $key => $val) {

if ($val['pid']) {

if(isset($list[$val['pid']])){

$list[$val['pid']]['children'][] = &$list[$key];

}

}

}

foreach($list as $key=>$val){

if($val['pid']) unset($list[$key]);

}

return array_values($list);

}

第二:递归(不推荐)

嵌套不能超过100重,否则报 Fatal error: Maximum function nesting level of '100' reached, aborting!function list_to_tree1($arr, $id=0){

$tree = array();

foreach($arr as $key=>$val) {

if($val['pid'] == $id) {

unset($arr[$key]);

$val['children'] = $this->list_to_tree1($arr, $val['id']);

if(empty($val['children'])){

unset($val['children']);

}

$tree[] = $val;

}

}

return $tree;

}

使用迭代和递归效果:$list = array(

0=>array('id'=>1,'pid'=>0,'name'=>'test1'),

1=>array('id'=>2,'pid'=>1,'name'=>'test2'),

2=>array('id'=>3,'pid'=>2,'name'=>'test3'),

3=>array('id'=>4,'pid'=>0,'name'=>'test4'),

4=>array('id'=>5,'pid'=>4,'name'=>'test5'),

5=>array('id'=>6,'pid'=>4,'name'=>'test6'),

);

$res = $this->list_to_tree($list);

//$res = $this->list_to_tree1($list);

print_r($res);

都输出:Array(

[0] => Array(

[id] => 1

[pid] => 0

[name] => test1

[children] => Array(

[0] => Array(

[id] => 2

[pid] => 1

[name] => test2

[children] => Array(

[0] => Array(

[id] => 3

[pid] => 2

[name] => test3

)

)

)

)

)

[1] => Array(

[id] => 4

[pid] => 0

[name] => test4

[children] => Array(

[0] => Array(

[id] => 5

[pid] => 4

[name] => test5

)

[1] => Array(

[id] => 6

[pid] => 4

[name] => test6

)

)

)

)

迭代和递归生成树的效率对比:

写一段代码模拟分类数据:2000条分类数据,层数3层$list = [];

for ($i=1;$i<=2000;$i=$i+3){

$list[] =array('id'=>$i,'pid'=>0,'name'=>'test'.$i);

$list[] =array('id'=>$i+1,'pid'=>$i,'name'=>'test'.($i+1));

$list[] =array('id'=>$i+2,'pid'=>$i+1,'name'=>'test'.($i+2));

}

测试效率:

1、迭代$start = microtime(true);

$res = $this->list_to_tree($list);

$end = microtime(true);

print_r(round($end-$start,3));

//用时:0.006秒

2、递归$start = microtime(true);

$res = $this->list_to_tree1($list);

$end = microtime(true);

print_r(round($end-$start,3));

//用时:1.942秒

原创文章,转载请注明出处:https://www.weizhixi.com/article/68.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值