Recursive Function to Construct Multidimensional Array from Database Result
Problem:
You seek a recursive function capable of transforming an array of pages and categories from a flattened database result into a nested array with structured hierarchical relationships.
Solution:
The provided solution offers a straightforward and generic approach:
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; }
Explanation:
The algorithm operates as follows:
Initial Execution (ParentId = 0):
Recursive Execution (ParentId != 0):
Building the Hierarchy:
Return Result:
By applying this function to your database result, you obtain an organized array with granular hierarchical relationships, as exemplified by your desired output. This approach is versatile and can be applied to both pages and categories.
The above is the detailed content of How to Recursively Build a Multidimensional Array from a Flat Database Result?. For more information, please follow other related articles on the PHP Chinese website!