Generating a Multidimensional Array from Database Results Using Recursive Function
To generate a nested array representing hierarchical data like pages or categories, a recursive function is often employed. The goal is to take a flat array of database records and transform it into a structured array reflecting the parent-child relationships.
Recursive Function for Tree Building
The following function, buildTree, achieves this task:
def buildTree(elements, parentId=0): branch = [] for element in elements: if element['parent_id'] == parentId: children = buildTree(elements, element['id']) if children: element['children'] = children branch.append(element) return branch
How It Works
Example Usage
To process your database records into a hierarchical tree, use:
tree = buildTree(database_result)
The tree variable will now contain a nested array representing the hierarchical structure of pages or categories.
The above is the detailed content of How Can a Recursive Function Build a Multidimensional Array from Flat Database Results?. For more information, please follow other related articles on the PHP Chinese website!