ClarkeRubber

Adding a Branch to a Tree

Dec 8th, 2013
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.09 KB | None | 0 0
  1. <?php
  2. function add_branch($tree, $branch){
  3.     /*
  4.     $tree is the pre-existing tree, and $branch is the branch that is to be added to the tree.
  5.     */
  6.     $temp = &$tree;
  7.     foreach($branch as $node){
  8.         if(array_key_exists($node, $temp)){
  9.             $temp = &$temp[$node];
  10.         }else{
  11.             $temp[$node] = array();
  12.             $temp = &$temp[$node];
  13.         }
  14.     }
  15.     return $tree;
  16. }
  17.  
  18. $tree = array();
  19. $branch = array("1", "2", "3", "4", "5");
  20. $tree = add_branch($tree, $branch);
  21.  
  22. $branch = array("1", "2", "5");
  23. $tree = add_branch($tree, $branch);
  24.  
  25. print_r($tree);
  26.  
  27. /*this produces:
  28. Array
  29. (
  30.     [1] => Array
  31.         (
  32.             [2] => Array
  33.                 (
  34.                     [3] => Array
  35.                         (
  36.                             [4] => Array
  37.                                 (
  38.                                     [5] => Array
  39.                                         (
  40.                                         )
  41.  
  42.                                 )
  43.  
  44.                         )
  45.  
  46.                     [5] => Array
  47.                         (
  48.                         )
  49.  
  50.                 )
  51.  
  52.         )
  53.  
  54. )
  55. */
Advertisement
Add Comment
Please, Sign In to add comment