Home > Backend Development > PHP Tutorial > How Can I Efficiently Build a Tree Structure from a Flat Array in PHP?

How Can I Efficiently Build a Tree Structure from a Flat Array in PHP?

Barbara Streisand
Release: 2024-12-02 15:33:15
Original
698 people have browsed it

How Can I Efficiently Build a Tree Structure from a Flat Array in PHP?

Build a Tree from a Flat Array in PHP

In PHP, it can be challenging to build a tree data structure from a flat array. However, this task can be simplified by applying recursion and an understanding of the parent-child relationship within the flat array.

Given a flat array where each element has an 'id' and a 'parent_id', the objective is to convert it into a hierarchical tree. Each element in the resulting tree should have a 'children' property if it has children elements.

Solution

The provided code attempts to create the tree recursively, but it fails to remove the element after adding it to the branch, resulting in multiple copies of the same element. To resolve this issue, we need to remove the element from the flat array after adding it to the branch.

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['id']] = $element;
            unset($elements[$element['id']]);
        }
    }

    return $branch;
}
Copy after login

Explanation

  1. We traverse the array, checking for elements that have the specified parent ID.
  2. If a matching element is found, we assign it to a variable and recurse to gather its children.
  3. If the element has children, we assign them to the 'children' property of the current element.
  4. After adding the element to the branch, we remove it from the flat array to prevent duplicates.
  5. We continue this process recursively until the entire tree is built.

The resulting array will be a hierarchical tree with each node containing its children as a nested array, providing a clear representation of the parent-child relationships in the original flat array.

The above is the detailed content of How Can I Efficiently Build a Tree Structure from a Flat Array in PHP?. 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