无限极子孙分类统计某个用户的层级子孙各有哪些 各有多少

it2022-07-05  197

在统计某个节点下有多少子孙节点,可以采用之前写的递归方式处理,当然觉得递归太复杂  可以采用循环解决,这里提供一个例子

 代码如下:

<?php $tree=array( array("id"=>"1", "name"=>"用户1" , "father_id"=>"0"), array("id"=>"2", "name"=>"用户2" , "father_id"=>"1"), array("id"=>"3", "name"=>"用户3" , "father_id"=>"2"), array("id"=>"4", "name"=>"用户4" , "father_id"=>"3"), array("id"=>"5", "name"=>"用户5" , "father_id"=>"1"), array("id"=>"6", "name"=>"用户6" , "father_id"=>"5"), array("id"=>"7", "name"=>"用户7" , "father_id"=>"6"), array("id"=>"8", "name"=>"用户8" , "father_id"=>"3"), array("id"=>"9", "name"=>"用户9" , "father_id"=>"4"), array("id"=>"10", "name"=>"用户10" , "father_id"=>"5"), array("id"=>"11", "name"=>"用户11" , "father_id"=>"6"), array("id"=>"12", "name"=>"用户12" , "father_id"=>"7"), array("id"=>"13", "name"=>"用户13" , "father_id"=>"2"), array("id"=>"14", "name"=>"用户14" , "father_id"=>"13"), array("id"=>"15", "name"=>"用户15" , "father_id"=>"2"), array("id"=>"16", "name"=>"用户16" , "father_id"=>"17"), array("id"=>"17", "name"=>"用户17" , "father_id"=>"5"), array("id"=>"18", "name"=>"用户18" , "father_id"=>"17"), array("id"=>"19", "name"=>"用户19" , "father_id"=>"18"), array("id"=>"20", "name"=>"用户20" , "father_id"=>"20"), array("id"=>"21", "name"=>"用户21" , "father_id"=>"3"), array("id"=>"22", "name"=>"用户22" , "father_id"=>"21"), array("id"=>"23", "name"=>"用户23" , "father_id"=>"6"), array("id"=>"24", "name"=>"用户24" , "father_id"=>"23"), array("id"=>"25", "name"=>"用户25" , "father_id"=>"9"), ); foreach ($tree as $key => $value) { $user_list[$value['id']]=$value['name']; $father_link[$value['father_id']][]=$value['id']; } function get_level_son($father_link=array(),$user_id=0,$level=1) { $father_list=array($user_id); for ($i=0; $i < $level; $i++) { $tmp_father=array(); foreach ($father_list as $key => $v) { if(isset($father_link[$v])) { $tmp_father=array_unique(array_merge($tmp_father,$father_link[$v]));//找子孙 } } $father_list=$tmp_father;//将子孙赋值给父亲 } return $father_list; } echo '<link href="https://cdn.bootcss.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" rel="stylesheet">'; echo "<div class='container'><table class='table table-striped table-bordered table-hover table-condensed' style='width:80%;'> <thead><tr><td>用户</td><td>1级子孙数量</td><td>1级子孙</td><td>2级子孙数量</td><td>2级子孙</td><td>3级子孙数量</td><td>3级子孙</td></tr></thead>"; echo "<tbody>"; foreach ($user_list as $key => $v) { $list1=get_level_son($father_link,$key,1); $list2=get_level_son($father_link,$key,2); $list3=get_level_son($father_link,$key,3); $count1=count($list1); $count2=count($list2); $count3=count($list3); echo "<tr> <td>".$v."</td> <td>".$count1."</td> <td>".implode(",",$list1)."</td> <td>".$count2."</td> <td>".implode(",",$list2)."</td> <td>".$count3."</td> <td>".implode(",",$list3)."</td> </tr>"; } echo "</tbody></table></div>"; ?>

运行效果如图:

 

转载于:https://www.cnblogs.com/lizhaoyao/p/7456862.html

相关资源:数据结构—成绩单生成器

最新回复(0)