Build a Tree from a Flat Array in PHP
In PHP, it can be challenging to build a tree data structure from a flat array. However, this task can be simplified by applying recursion and an understanding of the parent-child relationship within the flat array.
Given a flat array where each element has an 'id' and a 'parent_id', the objective is to convert it into a hierarchical tree. Each element in the resulting tree should have a 'children' property if it has children elements.
Solution
The provided code attempts to create the tree recursively, but it fails to remove the element after adding it to the branch, resulting in multiple copies of the same element. To resolve this issue, we need to remove the element from the flat array after adding it to the branch.
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['id']] = $element; unset($elements[$element['id']]); } } return $branch; }
Explanation
The resulting array will be a hierarchical tree with each node containing its children as a nested array, providing a clear representation of the parent-child relationships in the original flat array.
The above is the detailed content of How Can I Efficiently Build a Tree Structure from a Flat Array in PHP?. For more information, please follow other related articles on the PHP Chinese website!