Create tree structure in PHP


/ Published in: PHP
Save to your folder(s)

This snippet demonstrates how to build tree structure with PHP.


Copy this code and paste it in your HTML
  1. <?php
  2. class Node
  3. {
  4. public $depth = 0; //for printing
  5. public $parentNode = null; //reference to parent node
  6. public $text = ''; //display text
  7. public $children = array(); //children node(s)
  8.  
  9. function __construct($params = null)
  10. {
  11. foreach($params as $key=>$val)
  12. $this->$key = $val;
  13. if (isset($this->parentNode))
  14. $this->parentNode->addChild($this);
  15. }
  16. public function addChild(Node $node)
  17. {
  18. $this->children[] = $node;
  19. }
  20. }
  21. //-------------- end of class Node
  22. class Tree
  23. {
  24. public $root = null;
  25.  
  26. function __construct($maxLevel = 3)
  27. {
  28. $this->buildTree($maxLevel);
  29. }
  30.  
  31. public function buildTree($maxLevel = 3)
  32. {
  33. $this->root = new Node(array('text'=>'Root'));
  34. $this->populateChildren($this->root, 1, $maxLevel);
  35. }
  36.  
  37. public function printNodes()
  38. {
  39. $this->printChildren($this->root);
  40. }
  41.  
  42. private function printChildren(Node $node)
  43. {
  44. $N = $node->depth * 4;
  45. for ($idx = 0; $idx < $N; $idx++)
  46. echo '&nbsp;';
  47.  
  48. echo $node->text . "<br />\n";
  49. foreach($node->children as $child)
  50. $this->printChildren($child);
  51. }
  52.  
  53. private function populateChildren(Node $pnode, $level, $maxLevel)
  54. {
  55. //demonstrate how to populate tree's node
  56. if ($level <= $maxLevel)
  57. {
  58. for($idx = 0; $idx < $level; $idx++)
  59. {
  60. $child = new Node(array(
  61. 'parentNode'=> $pnode,
  62. 'text' => "$level::Node[$idx]",
  63. 'depth'=>$level)
  64. );
  65. $this->populateChildren($child, $level + 1, $maxLevel);
  66. }
  67. }
  68. }
  69. }
  70. //-------------- end of class Tree
  71.  
  72. //test displaying tree
  73. $tree = new Tree(4);
  74. $tree->printNodes();

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.