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!