下面的以zendframework 1为例
<?php
class Model_DbTable_Category extends Zend_Db_Table{
protected $_name="category";
protected $_primary="categoryId";
//获取某分类的直接子分类
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,$this->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,$this->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;
}
}
<?php
require_once ‘BaseController.php‘;
class CategoryController extends BaseController{
public function indexAction(){
$categoryModel=new Model_DbTable_Category();
$categorys=$categoryModel->fetchAll()->toArray();
//获取某分类的直接子分类
$result=$categoryModel->getSons($categorys,1);
foreach($result as $item)
echo $item[‘categoryName‘].‘<br>‘;
echo ‘<hr>‘;
//获取所欲分类的子分类
$result=$categoryModel->getSubs($categorys,0);
foreach($result as $item)
echo str_repeat(‘--‘,$item[‘level‘]).$item[‘categoryName‘].‘<br>‘;
echo ‘<hr>‘;
//获取某个分类的所有父分类
//方法一,递归
$result=$categoryModel->getParents($categorys,7);
foreach($result as $item)
echo $item[‘categoryName‘].‘ >> ‘;
echo ‘<hr>‘;
//获取某个分类的所有父分类
$result=$categoryModel->getParents2($categorys,15);
foreach($result as $item)
echo $item[‘categoryName‘].‘ >> ‘;
}
}
数据库部分
CREATE TABLE IF NOT EXISTS `sorts` (
`sid` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
`sparent` smallint(5) unsigned NOT NULL DEFAULT ‘0‘,
`name` varchar(50) NOT NULL,
PRIMARY KEY (`sid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=16 ;
INSERT INTO `sorts` (`sid`, `sparent`, `name`) 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++游戏开发‘);
实现效果图: