首先建立分类信息表:
- CREATE TABLE IF NOT EXISTS `category` (
- `categoryId` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
- `parentId` smallint(5) unsigned NOT NULL DEFAULT '0',
- `categoryName` varchar(50) NOT NULL,
- PRIMARY KEY (`categoryId`)
- ) ;
插入若干数据:
- INSERT INTO `category` (`categoryId`, `parentId`, `categoryName`) VALUES
- (1, 0, 'php'),
- (2, 0, 'java'),
- (3, 0, 'c/c++'),
- (4, 1, 'php基础'),
- (5, 1, 'php开源资料'),
- (6, 1, 'php框架'),
- (7, 2, 'java Se'),
- (8, 2, 'java EE'),
- (9, 2, 'java Me'),
- (10, 3, 'c/c++基础编程'),
- (11, 3, 'c/c++系统开发'),
- (12, 3, 'c嵌入式编程'),
- (13, 3, 'c++应用开发'),
- (14, 13, 'c++桌面应用开发'),
- (15, 13, 'c++游戏开发');
下面是php代码:
- <?php
- /*
- php无限极分类
- */
- //获取某分类的直接子分类
- function getSons($categorys,$catId=0){
- $sons=array();
- foreach($categorys as $item){
- if($item['parentId']==$catId)
- $sons[]=$item;
- }
- return $sons;
- }
- //获取某个分类的所有子分类
- function getSubs($categorys,$catId=0,$level=1){
- $subs=array();
- foreach($categorys as $item){
- if($item['parentId']==$catId){
- $item['level']=$level;
- $subs[]=$item;
- $subs=array_merge($subs,getSubs($categorys,$item['categoryId'],$level+1));
- }
- }
- return $subs;
- }
- //获取某个分类的所有父分类
- //方法一,递归
- function getParents($categorys,$catId){
- $tree=array();
- foreach($categorys as $item){
- if($item['categoryId']==$catId){
- if($item['parentId']>0)
- $tree=array_merge($tree,getParents($categorys,$item['parentId']));
- $tree[]=$item;
- break;
- }
- }
- return $tree;
- }
- //方法二,迭代
- function getParents2($categorys,$catId){
- $tree=array();
- while($catId != 0){
- foreach($categorys as $item){
- if($item['categoryId']==$catId){
- $tree[]=$item;
- $catId=$item['parentId'];
- break;
- }
- }
- }
- return $tree;
- }
- //测试 部分
- $pdo=new PDO('mysql:host=localhost;dbname=test','root','8888');
- $stmt=$pdo->query("select * from category order by categoryId");
- $categorys=$stmt->fetchAll(PDO::FETCH_ASSOC);
- $result=getSons($categorys,1);
- foreach($result as $item)
- echo $item['categoryName'].'<br>';
- echo '<hr>';
- $result=getSubs($categorys,0);
- foreach($result as $item)
- echo str_repeat(' ',$item['level']).$item['categoryName'].'<br>';
- echo '<hr>';
- $result=getParents($categorys,7);
- foreach($result as $item)
- echo $item['categoryName'].' >> ';
- echo '<hr>';
- $result=getParents2($categorys,15);
- foreach($result as $item)
- echo $item['categoryName'].' >> ';
- ?>
下面是运行的结果:
文章来源:http://blog.csdn.net/kankan231/article/details/8462349