无限极分类php实现—查子孙树、家谱树

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 .'
'; if($v['cat_id'] == $cat_id) { $num = 0; gettree($arr,$v['parent_id']); $list[] = $v; } } return $list; } $list = gettree($area,2); print_r($list); ?>


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 . '
'; 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'],'
'; } ?>


你可能感兴趣的:(数据结构,算法)