無限級の分類の子孫の木と家譜の木を探します

2560 ワード

子孫樹は指定した欄のすべての子類、および子類の子類を再帰的に検索し、家譜樹は制定欄の親類と親類の親類を検索し、トップクラスに一致する
'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