PHP 递归和迭代

2017-03-11  本文已影响0人  PHPNOTE

博客新开,什么都没有,先从印象笔记贴一篇以前的笔记

//用于操作的数据
$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 findson($arr,$id=0){
    $sons = array();
    foreach($arr as $k => $v){
        if ($v['parent'] == $id) {
            $sons[] = $v;
        }
    }
    return $sons;
}

print_r(findson($area,0));die;
//递归查找家谱树
function familytree($arr,$id){
    $tree = array();
    foreach ($arr as $k => $v) {
        if ($v['id'] == $id) {
            if ($v['parent'] > 0) {
            $tree =array_merge($tree,familytree($arr,$v['parent']));
            }
            $tree[] = $v;
        }
    }
    return $tree;
}
print_r(familytree($area,8));
//递归查找子孙树
function subtree($arr,$id,$lev=1){
    $subs = array();
    foreach($arr as $k => $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,1));
//迭代查找子孙树
function subtree($arr,$parent=0){
    $task = array($parent);//任务表
    $tree = array();//地区表
    while(!empty($task)){
        $flag = false;
        foreach ($arr as $k => $v) {
            if ($v['parent'] == $parent) {
                $tree[] = $v;
                array_push($task,$v['id']);//把最新的地区ID入任务栈
                $parent = $v['id'];
                unset($arr[$k]);//把找到的单元UNSET掉
                $flag = true;
            }
        }
        if ($flag == false) {
            array_pop($task);
            $parent = end($task);
        }
        print_r($task);
    }
    return $tree;
}

print_r(subtree($area,0));
上一篇下一篇

猜你喜欢

热点阅读