当前位置 : 主页 > 网络编程 > PHP >

二维数组转为树型数组,以及层级输出

来源:互联网 收集:自由互联 发布时间:2021-06-28
gistfile1.txt 1,'name'='AAA','pid'=0), array('id'= 2,'name'='BBB','pid'=0), array('id'= 3,'name'='CCC','pid'=0), array('id'= 4,'name'='aaa','pid'=1), array('id'= 5,'name'='bbb','pid'=2), array('id'= 6,'name'='ccc','pid'=3), array('id'= 7,'n
gistfile1.txt
  1,'name'=>'AAA','pid'=>0),
        array('id'=> 2,'name'=>'BBB','pid'=>0),
        array('id'=> 3,'name'=>'CCC','pid'=>0),
        array('id'=> 4,'name'=>'aaa','pid'=>1),
        array('id'=> 5,'name'=>'bbb','pid'=>2),
        array('id'=> 6,'name'=>'ccc','pid'=>3),
        array('id'=> 7,'name'=>'*aa','pid'=>4),
        array('id'=> 8,'name'=>'DDD','pid'=>0),
        array('id'=> 9,'name'=>'ddd','pid'=>1),
        array('id'=> 10,'name'=>'eee','pid'=>1),
        array('id'=> 11,'name'=>'**a','pid'=>7),
    );

//将数组转换成树形结构,传入数组和初始层级的父id,初始层级父id为:0
function getTreeFromArray($arr , $pid = 0){
    $tree = array();
    foreach ($arr as $k => $v){
        //遍历数组,如果当前元素父id与本层级的父id相等则加入$tree
        if($v['pid'] == $pid){
            $tree[$k] =  $arr[$k];
            //加入后删除该元素减少后序遍历次数,提升性能
            unset($arr[$k]); 
            //使用递归方式查找该元素的子节点数组
            $tree[$k]['son'] = getTreeFromArray($arr,$v['id']);
        }
    }
    return $tree;
}

//打印树形数组
function printTree($tree , $level = 0 ,$sign = "-->"){
    foreach ($tree as $k => $v){
        echo str_repeat($sign, $level);
        echo $v['name']."";
        if(!empty($v['son'])){
            printTree($v['son'],$level+1);
        }
    }
}

$tree = getTreeFromArray($data);
print_r($tree);
printTree($tree);
网友评论