Home > Backend Development > PHP Tutorial > How Can a Recursive Function Build a Multidimensional Array from Flat Database Results?

How Can a Recursive Function Build a Multidimensional Array from Flat Database Results?

Linda Hamilton
Release: 2024-12-30 06:15:12
Original
642 people have browsed it

How Can a Recursive Function Build a Multidimensional Array from Flat Database Results?

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
Copy after login

How It Works

  1. Initialize Branch: For a given parent ID, create an empty branch list to hold child elements.
  2. Iterate Over Elements: Loop through all elements in the flat array.
  3. Identify Children: If an element's parent_id matches the current parent ID, it's a child of the branch.
  4. Recurse for Children: Call the function recursively for the identified child, finding its sub-children.
  5. Add to Branch: Append the child element with its sub-children (if any) to the branch list.
  6. Return Branch: Once all children are processed, return the populated branch list.

Example Usage

To process your database records into a hierarchical tree, use:

tree = buildTree(database_result)
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template