实现线性结构转树形结构(生成无限层级菜单)

JS版

let list = [ 
    { parentId: 0, id: 1, value: '1' },
    { parentId: 3, id: 2, value: '2' }, 
    { parentId: 0, id: 3, value: '3' },
    { parentId: 1, id: 4, value: '4' }, 
    { parentId: 1, id: 5, value: '5' }, 
]; 

function listToTree(list){
    //遍历整个列表
    return list.filter(cur=>{ 
        // 获取当前节点的子节点
        let children= list.filter(item=> item.parentId == cur.id ); 
        if(children.length>0){
             cur.children=children;
        }
        //只返回顶级节点
        return cur.parentId==0; 
    });
}

console.log(listToTree(list));

PHP 版

无限级树形菜单及菜单渲染

表结构:
在这里插入图片描述
数据:
在这里插入图片描述
代码:

public function tree()
    { //演示结果
        $res = $this->get_tree();
        dump($res);//打印树形数组
        echo $this->render($res);//打印渲染后菜单
    }

    public function get_one_sub($pid)
    {//得到一级的下级
        $res = TestTrees::where("pid", $pid)->get();
        return $res->toArray();
    }

    public function get_tree($pid = 0)
    {//得到树形数组
        $c = $this->get_one_sub($pid);
        if ($c) {
            foreach ($c as &$v) {
                $v['c'] = $this->get_tree($v['id']);//递归
            }
        }
        return $c;
    }

    public function render($tree)
    {//渲染出菜单,实际上一般用js,但原理都是一样的
        static $i = 0;//表示菜单的级数
        $i = $i + 1;//每递归一次,菜单级数增加一级
        $str = "";//渲染结果
        $h = $i;//当前级数取出来,便于赋值
        foreach ($tree as $v) {
            $id = $v["id"];
            $pid = $v["pid"];
            if ($v['c']) {//如果有子级开始递归
                $con = $this->render($v['c']);//得到子级内容
            } else {
                $con = "";//得到子级内容
            }
            $cont = "<div style='border: solid black 1px;margin: 10px;'><span>$h 级菜单,id为 $id ,pid为 $pid </span>$con</div>";//得到当前级内容
            $str .= $cont;//同级别菜单合并
        }
        return $str;
    }

效果:
在这里插入图片描述
在这里插入图片描述

原文地址:https://www.cnblogs.com/lguow/p/15111850.html