php 二维数组重组成父与子关系

function buildTree(array $flat, $pidKey = 'pid', $idKey = 'id', $childrenKey = 'children') {
        $grouped = [];
        foreach ($flat as $sub) {
            $grouped[$sub[$pidKey]][] = $sub;
        }
        $fnBuilder = function(&$siblings) use ($grouped, $idKey, $childrenKey, &$fnBuilder) {
            foreach ($siblings as &$sibling) {
                $id = $sibling[$idKey];
                if (isset($grouped[$id])) {
                    $sibling[$childrenKey] = $grouped[$id];
                    $fnBuilder($sibling[$childrenKey]);
                }
            }
        };
        $tree = [];
        if (isset($grouped[0])) {
            $tree = $grouped[0];
            $fnBuilder($tree);
        }
        return $tree;
    }

 

posted @ 2023-04-27 09:12  楼前竹  阅读(30)  评论(0)    收藏  举报