📜  php 递归函数构建数组 - PHP 代码示例

📅  最后修改于: 2022-03-11 14:53:42.202000             🧑  作者: Mango

代码示例1
function buildTree(array $elements, $parentId = 0) {
    $branch = array();

    foreach ($elements as $element) {
        if ($element['parent_id'] == $parentId) {
            $children = buildTree($elements, $element['id']);
            if ($children) {
                $element['children'] = $children;
            }
            $branch[] = $element;
        }
    }

    return $branch;
}

$tree = buildTree($rows);