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 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!