首页 > 代码库 > 无限级分类之查找子孙树

无限级分类之查找子孙树

 1 <?php 
 2 header("Content-Type:text/html;charset=utf-8");
 3 $cate=array(
 4     array(‘id‘=>1,‘name‘=>‘html‘,‘parent‘=>0),
 5     array(‘id‘=>2,‘name‘=>‘javascript‘,‘parent‘=>0),
 6     array(‘id‘=>3,‘name‘=>‘div+css‘,‘parent‘=>0),
 7     array(‘id‘=>4,‘name‘=>‘linux‘,‘parent‘=>0),
 8     array(‘id‘=>5,‘name‘=>‘mysql‘,‘parent‘=>0),
 9     array(‘id‘=>6,‘name‘=>‘其他‘,‘parent‘=>0),
10     array(‘id‘=>7,‘name‘=>‘php‘,‘parent‘=>0),
11     array(‘id‘=>8,‘name‘=>‘字符串‘,‘parent‘=>7),
12     array(‘id‘=>9,‘name‘=>‘数组‘,‘parent‘=>7),
13     array(‘id‘=>10,‘name‘=>‘对象‘,‘parent‘=>7),
14     array(‘id‘=>11,‘name‘=>‘jquery‘,‘parent‘=>2),
15     array(‘id‘=>12,‘name‘=>‘ajax‘,‘parent‘=>2),
16     array(‘id‘=>13,‘name‘=>‘存储引擎‘,‘parent‘=>5),
17     array(‘id‘=>14,‘name‘=>‘事务‘,‘parent‘=>5),
18     array(‘id‘=>15,‘name‘=>‘存储过程‘,‘parent‘=>5),
19     array(‘id‘=>16,‘name‘=>‘视图‘,‘parent‘=>5),
20     array(‘id‘=>17,‘name‘=>‘基本命令‘,‘parent‘=>4),
21     array(‘id‘=>18,‘name‘=>‘网络配置‘,‘parent‘=>4)
22 );
23 
24 /*
25  * 利用静态变量来做
26  * static $con
27  */
28 
29 function findson($arr,$id=0,$lev=1){
30     static $con=array();
31     foreach ($arr as $v){
32         if ($v[‘parent‘]==$id){
33             $v[‘lev‘]=$lev;
34             $con[]=$v;
35             findson($arr,$v[‘id‘],$lev+1);
36         }
37     }
38     return $con;
39 }
40 
41 $arr=findson($cate,0,1);
42 
43 
44 foreach ($arr as $v){
45     if($v[‘lev‘]>1){
46         echo str_repeat("&nbsp;&nbsp;&nbsp;&nbsp;", $v[‘lev‘]).$v[‘name‘]."<br/>";
47     }else{
48         echo $v[‘name‘]."<br/>";
49     }
50    
51 }
52 
53 
54 /*
55  * 不用静态变量
56  */
57 
58 function findson($arr,$id=0,$lev=1){
59     $con=array();
60     foreach ($arr as $v){
61         if ($v[‘parent‘]==$id){
62             $v[‘lev‘]=$lev;
63             $con[]=$v;
64             $con=array_merge($con,findson($arr,$v[‘id‘],$lev+1));
65         }
66     }
67     return $con;
68 }
69 
70 $arr=findson($cate,0,1);
71 
72 
73 foreach ($arr as $v){
74     if($v[‘lev‘]>1){
75         echo str_repeat("&nbsp;&nbsp;&nbsp;&nbsp;", $v[‘lev‘]).$v[‘name‘]."<br/>";
76     }else{
77         echo $v[‘name‘]."<br/>";
78     }
79      
80 }
97 ?>

 

无限级分类之查找子孙树