C语言 c++ php mysql nginx linux lnmp lamp lanmp memcache redis 面试 笔记 ppt 设计模式 问题 远程连接

递归-树

$arr =     array(
          1 => array('id'=>'1','parentid'=>0,'name'=>'一级栏目一'),
          3 => array('id'=>'3','parentid'=>1,'name'=>'二级栏目一'),
          4 => array('id'=>'4','parentid'=>1,'name'=>'二级栏目二'),
          6 => array('id'=>'6','parentid'=>3,'name'=>'三级栏目一'),
          7 => array('id'=>'7','parentid'=>3,'name'=>'三级栏目二'),
          2 => array('id'=>'2','parentid'=>0,'name'=>'一级栏目二'),
          5 => array('id'=>'5','parentid'=>2,'name'=>'二级栏目三')
          );
//生成树
function create($pid, $arr)
{
    $ret = array();
    foreach($arr as $v)
    {
        if(isset($v['parentid']) && $v['parentid']==$pid)
        {
            $subret = array();
            $subret['id']  = $v['id'];
            $subret['name'] = $v['name'];
            $subret['children'] = create($v['id'], $arr);
            array_push($ret,$subret);
        }
    }
    return $ret;
}
$arr_tree = create(0,$arr);



//输出树
$i=1;
function echotree($arr_tree, $i)
{
    foreach($arr_tree as $k=>$v)
    {
        echo str_pad("",$i,"#").$v['name'].'<br/>';
        if(is_array($v['children'])){
            echotree($v['children'], $i+4);
            
        }
    }
}

echotree($arr_tree, $i);

 


posted on 2012-09-01 19:13  思齐_  阅读(226)  评论(0编辑  收藏  举报