$array = array(
    0=>array('id'=>1,'uid'=>0,'menuname'=>'菜单1','url'=>0,'addtime'=>'2018-08-29 16:36:55'),
    1=>array('id'=>2,'uid'=>0,'menuname'=>'菜单2','url'=>0,'addtime'=>'2018-08-29 16:36:55'),
    2=>array('id'=>3,'uid'=>1,'menuname'=>'1子菜单1','url'=>0,'addtime'=>'2018-08-29 16:36:55'),
    3=>array('id'=>4,'uid'=>3,'menuname'=>'1子菜单2','url'=>0,'addtime'=>'2018-08-29 16:36:55'),
    4=>array('id'=>5,'uid'=>2,'menuname'=>'2子菜单1','url'=>0,'addtime'=>'2018-08-29 16:36:55'),
);

 

(1) .递归实现

 function getTree($array, $pid =0, $level = 0){
    //声明静态数组,避免递归调用时,多次声明导致数组覆盖
    static $list = [];
    foreach ($array as $key => $value){
        //第一次遍历,找到父节点为根节点的节点 也就是pid=0的节点
        if ($value['pid'] == $pid){
            //父节点为根节点的节点,级别为0,也就是第一级
            $value['level'] = $level;
            //把数组放到list中
            $list[] = $value;
            //把这个节点从数组中移除,减少后续递归消耗
            unset($array[$key]);
            //开始递归,查找父ID为该节点ID的节点,级别则为原级别+1
           getTree($array, $value['id'], $level+1);
        }
    }
    return $list;
}

结果如图:

 

 

 

(2) .树结构

function getTree($items,$pid ="pid") {
    $map  = [];
    $tree = [];
    foreach ($items as &$it){ $map[$it['id']] = &$it; }  //数据的ID名生成新的引用索引树
    foreach ($items as &$at){
        $parent = &$map[$at[$pid]];
        if($parent) {
            $parent['children'][] = &$at;
        }else{
            $tree[] = &$at;
        }
    }
    return $tree;
}

 

结果如图: