Build a Tree from a Flat Array in PHP
A common task when working with hierarchical data structures is to convert a flat array into a tree-like structure. This can be done by identifying parent-child relationships and nesting elements accordingly.
One way to approach this is to iterate through the array and examine each element's parent_id value. If an element's parent_id is zero, it is considered a root level item. For other elements, their parent_ids can be used to determine their hierarchy within the tree.
To preserve the original array, it is recommended to create copies of elements as they are added to the tree. This can be achieved using the array_values() function.
Here's an example implementation:
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; }
To prevent duplicate elements in the resulting tree, it is crucial to unset the processed elements from the original array. This can be done by adding a line of code within the loop:
unset($elements[$element['id']]);
Using this revised function, the flat array can be converted into a hierarchical tree structure. The result will be an array with nested child elements under each parent element.
The above is the detailed content of How to Build a Tree Structure from a Flat Array in PHP?. For more information, please follow other related articles on the PHP Chinese website!