无限级分类之查找子孙树,面包屑导航

Post Time:2018-02-12 13:51:04 Views:716

效果演示: 安徽ID=1 parent=0 淮北ID=5 parent=1 淮溪县ID=3 parent=5 北京ID=7 parent=0 海淀ID=2 parent=7 上地ID=8 parent=2 昌平ID=4 parent=7 朝阳ID=6 parent=7

<?php
$area = array(
	array('id' => 1,'name' => '安徽','parent' => 0),
	array('id' => 2,'name' => '海淀','parent' => 7),
	array('id' => 3,'name' => '淮溪县','parent' => 5),
	array('id' => 4,'name' => '昌平','parent' => 7),
	array('id' => 5,'name' => '淮北','parent' => 1),
	array('id' => 6,'name' => '朝阳','parent' => 7),
	array('id' => 7,'name' => '北京','parent' => 0),
	array('id' => 8,'name' => '上地','parent' => 2)
);

function subtree($arr,$id=0,$lev=1){
	//static $subs = array();//子孙数组用静态属性保存
	$subs = array();

	foreach ($arr as $v) {
		if ($v['parent'] == $id) {
		    $v['lev'] = $lev;
			$subs[] = $v;
			$subs = array_merge($subs,subtree($arr,$v['id'],$lev+1));
		}
	}

	return $subs;
}

//print_r(subtree($area,0,1));
$tree = subtree($area,0,1);
foreach($tree as $v){
    echo str_repeat('  ',$v['lev']),$v['name'],'ID=',$v['id'],' parent=',$v['parent'],'<br>';
}
<?php
$area = array(
	array('id' => 1,'name' => '安徽','parent' => 0),
	array('id' => 2,'name' => '海淀','parent' => 7),
	array('id' => 3,'name' => '淮溪县','parent' => 5),
	array('id' => 4,'name' => '昌平','parent' => 7),
	array('id' => 5,'name' => '淮北','parent' => 1),
	array('id' => 6,'name' => '朝阳','parent' => 7),
	array('id' => 7,'name' => '北京','parent' => 0),
	array('id' => 8,'name' => '上地','parent' => 2)
);

function familyTree($arr,$id){
    static $tree = array();
    
    foreach($arr as $v){
        if($v['id'] == $id){
            $tree[] = $v;
            if($v['parent'] > 0){
                familyTree($arr,$v['parent']);
            }
        }
    }
    return $tree;
}

print_r(familyTree($area,8));
Comments: 0
暂无评论

「人生在世,留句话给我吧」

撰写评论