<?php
// 无限级分类中,查家谱树
$area = array(
0=>array('cat_id'=>1,'cat_name'=>'北京市','parent_id'=>0),
1=>array('cat_id'=>2,'cat_name'=>'馆陶县','parent_id'=>5),
2=>array('cat_id'=>3,'cat_name'=>'海淀区','parent_id'=>1),
3=>array('cat_id'=>4,'cat_name'=>'朝阳区','parent_id'=>1),
4=>array('cat_id'=>5,'cat_name'=>'邯郸市','parent_id'=>6),
5=>array('cat_id'=>6,'cat_name'=>'河北省','parent_id'=>0),
);
function gettree($arr,$cat_id) {
static $list = array();
static $num = 0;
foreach($arr as $v) {
echo ++$num .'<br />';
if($v['cat_id'] == $cat_id) {
$num = 0;
gettree($arr,$v['parent_id']);
$list[] = $v;
}
}
return $list;
}
$list = gettree($area,2);
print_r($list);
?>
<?php
// 无限级分类中,查找子孙树
$area = array(
0=>array('cat_id'=>1,'cat_name'=>'北京市','parent_id'=>0),
1=>array('cat_id'=>2,'cat_name'=>'馆陶县','parent_id'=>5),
2=>array('cat_id'=>3,'cat_name'=>'海淀区','parent_id'=>1),
3=>array('cat_id'=>4,'cat_name'=>'朝阳区','parent_id'=>1),
4=>array('cat_id'=>5,'cat_name'=>'邯郸市','parent_id'=>6),
5=>array('cat_id'=>6,'cat_name'=>'河北省','parent_id'=>0),
);
function catsort($arr,$parent_id = 0,$lev=1) {
static $list = array();
static $num = 0;
foreach($arr as $v) {
echo ++$num . '<br />';
if($v['parent_id'] == $parent_id) {
$num = 0;
$v['lev'] = $lev;
$list[] = $v;
catsort($arr,$v['cat_id'],$lev+1);
}
}
return $list;
}
$list = catsort($area,0,1);
foreach($list as $v) {
echo str_repeat(' ',$v['lev']),$v['cat_name'],'<br />';
}
?>
本文来自博客园,作者:孙龙-程序员,转载请注明原文链接:https://www.cnblogs.com/sunlong88/articles/8681469.html