Home >Backend Development >PHP Tutorial >How to Convert Parent-Child Relationships into Hierarchical Trees in PHP?

How to Convert Parent-Child Relationships into Hierarchical Trees in PHP?

Linda Hamilton
Linda HamiltonOriginal
2024-12-26 09:57:10413browse

How to Convert Parent-Child Relationships into Hierarchical Trees in PHP?

Converting Parent-Child Relationships into Hierarchical Trees

In programming, it can be necessary to convert a series of parent-child relationships into a hierarchical tree structure. This task can be accomplished in PHP using a recursive approach.

Example Data:

Consider the following set of parent-child relationships:

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

Transforming into Hierarchical Tree:

To transform this data into a hierarchical tree structure, we create two PHP functions:

  • parseTree($tree, $root): This function recursively parses the child-parent pairs and constructs the tree.
  • printTree($tree): This function traverses the tree and prints it as an unordered list.

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;    
}

printTree Function:

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>';
    }
}

Usage:

To use these functions, first initialize the array of child-parent pairs. Then call parseTree with the array and printTree with the resulting tree:

$tree = array(
    'H' => 'G',
    'F' => 'G',
    'G' => 'D',
    'E' => 'D',
    'A' => 'E',
    'B' => 'C',
    'C' => 'E',
    'D' => null
);

$result = parseTree($tree);
printTree($result);

Result:

The output will be an unordered list representing the hierarchical tree:

<ul>
<li>D
<ul>
<li>G
<ul>
<li>H</li>
<li>F</li>
</ul>
</li>
<li>E
<ul>
<li>A</li>
<li>C
<ul>
<li>B</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>

The above is the detailed content of How to Convert Parent-Child Relationships into Hierarchical Trees in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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