Posted By

putu on 02/28/12


Tagged

oop recursive tree


Versions (?)

Create tree structure in PHP


 / Published in: PHP
 

This snippet demonstrates how to build tree structure with PHP.

  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
Posted By: TungNguyenDam on October 27, 2012

$data = array(

 array('id' => 1, 'pid' => 0, 'name' => 'node1', ...),
 array('id' => 2, 'pid' => 0, 'name' => 'node2', ...),
 array('id' => 3, 'pid' => 1, 'name' => 'node1.1', ...),
 array('id' => 4, 'pid' => 3, 'name' => 'node1.1.1', ...)
 ...

);

OR

$data = array();

while($row = mysqlfetcharray(mysqlquery('SELECT * FROM categories ORDER BY RAND()'), MYSQLASSOC)){

 $data[] = $row;

}

// Create dynamic tree

function create($data){

foreach($data as &$v){

    // Get childs

    if(isset(self::$tree[$v['id']])) $v['child'] =& self::$tree[$v['id']];


    // push node into parent

    self::$tree[$v['pid']][$v['id']] =& $v;             


    // push child into node

    self::$tree[$v['id']]   =& $v['child'];

}


// return Tree

return self::$tree[0];

}

You need to login to post a comment.