How to create multi-dimensional array from a list?

Some very simple recursion to build a tree structure:

function buildTree(array $data, $parent = null) {
    $branch = array();

    foreach ($data as $row) {
        if ($row['parent_id'] == $parent) {
            $row['children'] = buildTree($data, $row['id']);
            $branch[] = $row;
        }
    }

    return $branch;
}

$tree = buildTree($rowsFromDatabase);

Having an explicit 'children' key is usually preferable to the structure you’re proposing, but feel free to modify as needed.

Leave a Comment