How to Build a Hierarchical Tree Structure from a Flat Array in PHP?

Barbara Streisand
Release: 2024-11-27 18:33:15
Original
183 people have browsed it

How to Build a Hierarchical Tree Structure from a Flat Array in PHP?

Building a Tree Structure from a Flat Array in PHP

Problem:

You have a flat array consisting of elements with 'id' and 'parent_id' fields, where each element may have at most one parent and zero or more children. When 'parent_id' is 0, the element is a root level item. The goal is to restructure this flat array into a hierarchical tree with child-parent relationships.

Solution:

The provided function, buildTree(), effectively accomplishes this task by iterating through the input array and recursively building the tree structure. Each element in the output tree contains its ID, parent ID, and an array of child elements.

Implementation:

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

    return $branch;
}
Copy after login

The 'unset' Call:

In the code above, the unset() call is crucial for maintaining the hierarchical structure. It removes processed elements from the original input array, ensuring that elements are not duplicated in the tree.

Example:

Consider the provided input array:

[_319_] => [...],
[_320_] => [...],
[_321_] => [...],
[_322_] => [...],
[_323_] => [...],
[_324_] => [...],
[_325_] => [...]
Copy after login

After processing, the output tree maintains the parent-child relationships:

[_319_] => [...],
[_320_] => [
    'id' => '_320_',
    'parent_id' => 0,
    'children' => [
        [_321_] => [...],
        [_325_] => [...]
    ]
],
[_323_] => [
    'id' => '_323_',
    'parent_id' => 0,
    'children' => [
        [_324_] => [...]
    ]
]
Copy after login

Therefore, the buildTree() function enables you to transform a flat array of elements with parent-child relationships into a structured hierarchical tree in PHP.

The above is the detailed content of How to Build a Hierarchical 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