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