Recursive Function to Generate Multidimensional Array from Database Result
Problem:
Building nested arrays hierarchically from a flat result table, where each row represents an item with its parent ID.
Solution:
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;
}
$tree = buildTree($rows);
Copy after login
Explanation:
The algorithm iteratively builds a hierarchical tree structure using recursion:
- It initializes an empty array $branch to store the current level of the tree.
- It iterates through the elements and checks if an element's parent_id matches the specified $parentId.
- If a match is found, it means the element is a child of the current parent and should be added to the $branch.
- It recursively calls the buildTree function with the element's id as the new $parentId to find its children.
- If any children are found, they are added as a sub-array to the current element.
- After processing all children, the $branch array is returned to represent the next level of the hierarchy.
- The initial call to buildTree with an initial $parentId of 0 fetches the root elements of the hierarchy, and the recursive calls populate the nested structure.
The above is the detailed content of How Can a Recursive Function Create a Multidimensional Array from a Flat Database Result?. For more information, please follow other related articles on the PHP Chinese website!