img

thinkphp5 递归实现菜单栏

2022-04-20 0条评论 3k次阅读 PHP


<?php
class Index
{
    private static function arr()
    {
        $rows = array(
            array(
                'id' => '1',
                'name' => '一级菜单',
                'pid' => '0',
                'path' => '0',
            ),
            array(
                'id' => '2',
                'name' => '二级菜单',
                'pid' => '0',
                'path' => '0',
            ),
            array(
                'id' => '3',
                'name' => '一级菜单-1',
                'pid' => '1',
                'path' => '0-1',
            ),
            array(
                'id' => '4',
                'name' => '二级菜单-1',
                'pid' => '2',
                'path' => '0-2',
            ),
            array(
                'id' => '5',
                'name' => '一级菜单-1-1',
                'pid' => '3',
                'path' => '0-1-3',
            ),
            array(
                'id' => '6',
                'name' => '二级菜单-1-1',
                'pid' => '4',
                'path' => '0-2-4',
            ),
            array(
                'id' => '7',
                'name' => '二级菜单-1-2',
                'pid' => '4',
                'path' => '0-2-4',
            ),
            array(
                'id' => '8',
                'name' => '三级菜单',
                'pid' => '0',
                'path' => '0',
            ),
            array(
                'id' => '9',
                'name' => '二级菜单-1-3',
                'pid' => '4',
                'path' => '0-2-4-6',
            ),
            array(
                'id' => '10',
                'name' => '三级菜单-1',
                'pid' => '8',
                'path' => '0-8',
            ),
            array(
                'id' => '11',
                'name' => '三级菜单-1',
                'pid' => '0',
                'path' => '0',
            ),
        );
        return $rows;
    }

    // 递归子级
    public function findchild(&$arr, $id)
    {
        $childs = array();
        foreach ($arr as $key => $value) {
            if ($value['pid'] == $id) {
                $childs[] = $value;
            }
        }
        return $childs;
    }

    // 查找当前级别的子级
    public function build_tree($root_id)
    {
        $rows = $this->arr();
        $childs = $this->findchild($rows, $root_id);
        if (empty($childs)) {
            return null;
        }
        foreach ($childs as $key => $value) {
            $rescurTree = $this->build_tree($value['id']);
            if (null != $rescurTree) {
                $childs[$key]['childs'] = $rescurTree;
            }
        }
        return $childs;
    }

    public function getDg()
    {
        $dg = $this->build_tree("0");
        return $dg;
    }
}
$r = new Index();
$res = $r->getDg();
echo "<pre>" . print_r($res, true) . "</pre>";

转载于:https://blog.csdn.net/dashanjv/article/details/105778694

💬 COMMENT


🦄 支持markdown语法

👋友