鍍金池/ 問(wèn)答/人工智能  PHP/ 權(quán)限列表的循環(huán)

權(quán)限列表的循環(huán)

如題我有一個(gè)查詢(xún)會(huì)查出當(dāng)前用戶(hù)所有的權(quán)限

$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']
];

我想重新組織這個(gè)數(shù)組使它根據(jù)pid變成樹(shù)形結(jié)構(gòu),就像這樣

$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'
                            ]
                    ],
                ]
            ],
        ],
    ],

];

請(qǐng)問(wèn)大家有沒(méi)有什么要率高的算法?

回答
編輯回答
墨染殤

從so找來(lái)的答案, 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);
2017年2月20日 07:29