权限列表的循环

如题我有一个查询会查出当前用户所有的权限

$authList = [
    ['id' => 1, 'pid' => 0, 'title' => 'project'],
    ['id' => 2, 'pid' => 0, 'title' => 'customer'],
    ['id' => 3, 'pid' => 1, 'title' => 'select'],
    ['id' => 4, 'pid' => 1, 'title' => 'delete'],
    ['id' => 5, 'pid' => 2, 'title' => 'select'],
    ['id' => 6, 'pid' => 2, 'title' => 'delete'],
    ['id' => 7, 'pid' => 6, 'title' => 'logic delete']
];

我想重新组织这个数组使它根据pid变成树形结构,就像这样

$result = [
    [
        'id' => 1,
        'pid' => 0,
        'title' => 'project',
        'children' => [
            [
                'id' => 3,
                'pid' => 1,
                'title' => 'select'
            ],
            [
                'id' => 4,
                'pid' => 1,
                'title' => 'delete'
            ],
        ]
    ],
    [
        [
            'id' => 2,
            'pid' => 0,
            'title' => 'customer',
            'children' => [
                [
                    'id' => 5,
                    'pid' => 2,
                    'title' => 'select'
                ],
                [
                    'id' => 6,
                    'pid' => 2,
                    'title' => 'delete',
                    'children' => [
                        [
                            'id' => 7,
                            'pid' => 6,
                            'title' => 'logic delete'
                            ]
                    ],
                ]
            ],
        ],
    ],

];

请问大家有没有什么要率高的算法?

阅读 1.8k
1 个回答

从so找来的答案, https://implode.io/yTyHaP


function buildTree(array &$elements, $parentId = 0) {

    $branch = array();

    foreach ($elements as &$element) {

        if ($element['pid'] == $parentId) {
            $children = buildTree($elements, $element['id']);
            if ($children) {
                $element['children'] = $children;
            }
            $branch[$element['id']] = $element;
            unset($element);
        }
    }
    return $branch;
}

$authList = [
    ['id' => 1, 'pid' => 0, 'title' => 'project'],
    ['id' => 2, 'pid' => 0, 'title' => 'customer'],
    ['id' => 3, 'pid' => 1, 'title' => 'select'],
    ['id' => 4, 'pid' => 1, 'title' => 'delete'],
    ['id' => 5, 'pid' => 2, 'title' => 'select'],
    ['id' => 6, 'pid' => 2, 'title' => 'delete'],
    ['id' => 7, 'pid' => 6, 'title' => 'logic delete']
];

return buildTree($authList);
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题