php之无限极分类

首先建立分类信息表:

1 CREATE TABLE IF NOT EXISTS `category` (
2   `categoryId` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
3   `parentId` smallint(5) unsigned NOT NULL DEFAULT 0,
4   `categoryName` varchar(50) NOT NULL,
5   PRIMARY KEY (`categoryId`)
6 )  ;

插入若干数据:

 1 INSERT INTO `category` (`categoryId`, `parentId`, `categoryName`) VALUES
 2 (1, 0, php),
 3 (2, 0, java),
 4 (3, 0, c/c++),
 5 (4, 1, php基础),
 6 (5, 1, php开源资料),
 7 (6, 1, php框架),
 8 (7, 2, java Se),
 9 (8, 2, java EE),
10 (9, 2, java Me),
11 (10, 3, c/c++基础编程),
12 (11, 3, c/c++系统开发),
13 (12, 3, c嵌入式编程),
14 (13, 3, c++应用开发),
15 (14, 13, c++桌面应用开发),
16 (15, 13, c++游戏开发);

下面是php代码:

 1 <?php
 2 //php无限级分类
 3 
 4 //获取某分类的直接子分类
 5 function getSons($categorys,$catId=0){
 6     $sons=array();
 7     foreach($categorys as $item){
 8         if($item[‘parentId‘]==$catId)
 9             $sons[]=$item;
10     }
11     return $sons;
12 }
13 
14 //获取某个分类的所有子分类
15 function getSubs($categorys,$catId=0,$level=1){
16     $subs=array();
17     foreach($categorys as $item){
18         if($item[‘parentId‘]==$catId){
19             $item[‘level‘]=$level;
20             $subs[]=$item;
21             $subs=array_merge($subs,getSubs($categorys,$item[‘categoryId‘],$level+1));
22             
23         }
24             
25     }
26     return $subs;
27 }
28 
29 //获取某个分类的所有父分类
30 //方法一,递归
31 function getParents($categorys,$catId){
32     $tree=array();
33     foreach($categorys as $item){
34         if($item[‘categoryId‘]==$catId){
35             if($item[‘parentId‘]>0)
36                 $tree=array_merge($tree,getParents($categorys,$item[‘parentId‘]));
37             $tree[]=$item;    
38             break;    
39         }
40     }
41     return $tree;
42 }
43 
44 //方法二,迭代
45 function getParents2($categorys,$catId){
46     $tree=array();
47     while($catId != 0){
48         foreach($categorys as $item){
49             if($item[‘categoryId‘]==$catId){
50                 $tree[]=$item;
51                 $catId=$item[‘parentId‘];
52                 break;    
53             }
54         }
55     }
56     return $tree;
57 }
58 
59 
60 //测试 部分
61 $pdo=new PDO(‘mysql:host=localhost;dbname=test‘,‘root‘,‘8888‘);
62 $stmt=$pdo->query("select * from category order by categoryId");
63 $categorys=$stmt->fetchAll(PDO::FETCH_ASSOC);
64 
65 $result=getSons($categorys,1);
66 foreach($result as $item)
67     echo $item[‘categoryName‘].‘<br>‘;
68 echo ‘<hr>‘;
69 
70 $result=getSubs($categorys,0);
71 foreach($result as $item)
72     echo str_repeat(‘  ‘,$item[‘level‘]).$item[‘categoryName‘].‘<br>‘;
73 echo ‘<hr>‘;
74 
75 $result=getParents($categorys,7);
76 foreach($result as $item)
77     echo $item[‘categoryName‘].‘ >> ‘;
78 echo ‘<hr>‘;
79 
80 $result=getParents2($categorys,15);
81 foreach($result as $item)
82     echo $item[‘categoryName‘].‘ >> ‘;
83 ?>

下面是运行的结果:

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。