/ Published in: PHP
This snippet demonstrates how to build tree structure with PHP.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
<?php class Node { public $depth = 0; //for printing public $parentNode = null; //reference to parent node public $text = ''; //display text function __construct($params = null) { foreach($params as $key=>$val) $this->$key = $val; $this->parentNode->addChild($this); } public function addChild(Node $node) { $this->children[] = $node; } } //-------------- end of class Node class Tree { public $root = null; function __construct($maxLevel = 3) { $this->buildTree($maxLevel); } public function buildTree($maxLevel = 3) { $this->populateChildren($this->root, 1, $maxLevel); } public function printNodes() { $this->printChildren($this->root); } private function printChildren(Node $node) { $N = $node->depth * 4; for ($idx = 0; $idx < $N; $idx++) echo ' '; echo $node->text . "<br />\n"; foreach($node->children as $child) $this->printChildren($child); } private function populateChildren(Node $pnode, $level, $maxLevel) { //demonstrate how to populate tree's node if ($level <= $maxLevel) { for($idx = 0; $idx < $level; $idx++) { 'parentNode'=> $pnode, 'text' => "$level::Node[$idx]", 'depth'=>$level) ); $this->populateChildren($child, $level + 1, $maxLevel); } } } } //-------------- end of class Tree //test displaying tree $tree = new Tree(4); $tree->printNodes();