Building a Tree Structure from a Flat Array in PHP
Problem:
You have a flat array consisting of elements with 'id' and 'parent_id' fields, where each element may have at most one parent and zero or more children. When 'parent_id' is 0, the element is a root level item. The goal is to restructure this flat array into a hierarchical tree with child-parent relationships.
Solution:
The provided function, buildTree(), effectively accomplishes this task by iterating through the input array and recursively building the tree structure. Each element in the output tree contains its ID, parent ID, and an array of child elements.
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; unset($elements[$element['id']]); } } return $branch; }
The 'unset' Call:
In the code above, the unset() call is crucial for maintaining the hierarchical structure. It removes processed elements from the original input array, ensuring that elements are not duplicated in the tree.
Example:
Consider the provided input array:
[_319_] => [...], [_320_] => [...], [_321_] => [...], [_322_] => [...], [_323_] => [...], [_324_] => [...], [_325_] => [...]
After processing, the output tree maintains the parent-child relationships:
[_319_] => [...], [_320_] => [ 'id' => '_320_', 'parent_id' => 0, 'children' => [ [_321_] => [...], [_325_] => [...] ] ], [_323_] => [ 'id' => '_323_', 'parent_id' => 0, 'children' => [ [_324_] => [...] ] ]
Therefore, the buildTree() function enables you to transform a flat array of elements with parent-child relationships into a structured hierarchical tree in PHP.
The above is the detailed content of How to Build a Hierarchical Tree Structure from a Flat Array in PHP?. For more information, please follow other related articles on the PHP Chinese website!