首页 > 代码库 > php之无限极分类
php之无限极分类
首先建立分类信息表:
[sql] view plaincopy
- 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`)
- ) ;
插入若干数据:
[sql] view plaincopy
- 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] view plaincopy
- <?php
- /*
[php] view plaincopy
- php无限极分类
[php] view plaincopy
- */
- //获取某分类的直接子分类
- 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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。