Home > Backend Development > PHP Tutorial > How Can I Build a Hierarchical Tree Structure in PHP from Parent-Child Relationships?

How Can I Build a Hierarchical Tree Structure in PHP from Parent-Child Relationships?

Mary-Kate Olsen
Release: 2024-12-14 11:41:11
Original
229 people have browsed it

How Can I Build a Hierarchical Tree Structure in PHP from Parent-Child Relationships?

Hierarchical Tree Structure Creation from Parent-Child Relationships

Constructing hierarchical tree structures from parent-child relationships is a common task in programming. To achieve this, a recursive approach can be employed, effectively organizing the data into nested units.

In PHP, converting a series of parent-child pairs into a hierarchical tree requires two key functions: parsing and printing. The parsing function systematically traverses the child-parent pairs to build a hierarchical data structure. Following this, the printing function converts this structure into a series of nested HTML unordered lists, with each list item representing a child.

As an example, consider the following parent-child pairs:

Child : Parent
H : G
F : G
G : D
E : D
A : E
B : C
C : E
D : NULL
Copy after login

To parse this data, we define the parseTree function:

function parseTree($tree, $root = null) {
    $return = array();
    foreach($tree as $child => $parent) {
        if($parent == $root) {
            unset($tree[$child]);
            $return[] = array(
                'name' => $child,
                'children' => parseTree($tree, $child)
            );
        }
    }
    return empty($return) ? null : $return;
}
Copy after login

Next, we define the printTree function to convert the parsed hierarchy into HTML unordered lists:

function printTree($tree) {
    if(!is_null($tree) && count($tree) > 0) {
        echo '<ul>';
        foreach($tree as $node) {
            echo '<li>'.$node['name'];
            printTree($node['children']);
            echo '</li>';
        }
        echo '</ul>';
    }
}
Copy after login

By combining these two functions, we can successfully convert child-parent pairs into hierarchical tree structures.

The above is the detailed content of How Can I Build a Hierarchical Tree Structure in PHP from Parent-Child Relationships?. 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