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

How Can a Recursive Function Create a Multidimensional Array from a Flat Database Result?

DDD
Release: 2024-12-15 20:59:15
Original
554 people have browsed it

How Can a Recursive Function Create a Multidimensional Array from a Flat Database Result?

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:

  1. It initializes an empty array $branch to store the current level of the tree.
  2. It iterates through the elements and checks if an element's parent_id matches the specified $parentId.
  3. If a match is found, it means the element is a child of the current parent and should be added to the $branch.
  4. It recursively calls the buildTree function with the element's id as the new $parentId to find its children.
  5. If any children are found, they are added as a sub-array to the current element.
  6. After processing all children, the $branch array is returned to represent the next level of the hierarchy.
  7. 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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template