无限级分类之查找子孙树和家谱树

子孙树是用递归查找指定栏目的所有子类,以及子类的子类,查找家谱树是查找制定栏目的父类和父类的父类,一致到顶级类

'1','name'=>'河南','parent'=>0),
    array('id'=>'2','name'=>'吉林','parent'=>0),
    array('id'=>'3','name'=>'北京','parent'=>0),
    array('id'=>'4','name'=>'信阳','parent'=>1),
    array('id'=>'5','name'=>'郑州','parent'=>1),
    array('id'=>'6','name'=>'长春','parent'=>2),
    array('id'=>'7','name'=>'朝阳','parent'=>3),
    array('id'=>'8','name'=>'海淀','parent'=>3)
    );
//无限级分类之找子孙树
function subtree($arr,$id,$lev=1){
    static $subs=array();//子孙数组

    foreach ($arr as $v) {
        if($v['parent']==$id){
            $v['lev']=$lev;
            $subs[]=$v;
            subtree($arr,$v['id'],$lev+1);
        }
    }
    return $subs;
}
$tree =subtree($area,0,1);
foreach ($tree as $v) {
    echo str_repeat('  ', $v['lev']),$v['name'],'
'; } // 若不用static,可以用array_merge()将数组连接起来 function subtree2($arr,$id,$lev=1){ $subs=array();//子孙数组 foreach ($arr as $v) { if($v['parent']==$id){ $v['lev']=$lev; $subs[]=$v; $subs=array_merge($subs,subtree2($arr,$v['id'],$lev+1)); } } return $subs; } $tree2 =subtree2($area,0,1); foreach ($tree2 as $v) { echo str_repeat('  ', $v['lev']),$v['name'],'
'; } // 无限极分类之查找家谱树 function familytree($arr,$id){ static $tree=array(); foreach($arr as $v){ if($v['id']==$id){ //判断要不要找父栏目 if($v['parent']>0){ familytree($arr,$v['parent']); } $tree[]=$v; } } return $tree; } $fam=familytree($area,4); print_r($fam); // 迭代找家谱树 function famtree($arr,$id){ $tree=array(); while($id!==0){ foreach($arr as $v){ if($v['id']==$id){ $tree[]=$v; $id=$v['parent']; break; } } } return $tree; } print_r(famtree($area,4)); ?>

 

转载于:https://www.cnblogs.com/lzzhuany/p/4773128.html

你可能感兴趣的:(php)