Home >Backend Development >PHP Tutorial >How to Efficiently Create a Nested Array Tree from a Flat Array List?

How to Efficiently Create a Nested Array Tree from a Flat Array List?

Susan Sarandon
Susan SarandonOriginal
2024-12-25 18:50:10724browse

How to Efficiently Create a Nested Array Tree from a Flat Array List?

Creating a Nested Array Tree from an Array List

You have an array of elements with parent-child relationships and wish to transform it into a nested array tree. Here's an efficient solution:

# Create a new array indexed by parent ID
$new = [];
foreach ($arr as $a) {
    $new[$a['parentid']][] = $a;
}

# Start with the root node
$tree = createTree($new, [$arr[0]]);

# Recursive function to build the tree
function createTree(&$list, $parent) {
    $tree = [];
    foreach ($parent as $l) {
        # If there are children, create children tree
        if (isset($list[$l['id']])) {
            $l['children'] = createTree($list, $list[$l['id']]);
        }

        # Add parent to the tree
        $tree[] = $l;
    }
    return $tree;
}

This algorithm efficiently constructs a nested array tree based on the parent-child relationships in your original array.

The above is the detailed content of How to Efficiently Create a Nested Array Tree from a Flat Array List?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn