Re: Display Array Tree as Menu - Can't figure out how to finddepth with something over 2 levels : ANSWERED

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On 16-08-2012 20:28, Tristan wrote:
Thanks for all your help. The answer was so simple in the end. Thanks Tim
for clearing that up!!! Perfect little script now for creating navigation.
Just feed it an array like posted at the bottom of this message.

function createTree(&$list, $parent){

     global $depth;

     $depth++; // Increment as we descend

     $tree = array();
//$depth = 0;
     foreach ($parent as $k=>$l){
$l['depth'] = $depth;
         if(isset($list[$l['section_id']])){
             $l['children'] = createTree($list, $list[$l['section_id']]);
         }
         $tree[] = $l;
     }

     $depth--; // Decrement as we ascend

     return $tree;
}

$arr = $dashSections;

$new = array();
foreach ($arr as $a){
     $new[$a['section_parent_id']][] = $a;
}

// CREATE THE TREE
$depth = 0;

$tree = createTree($new, $new[0]);
//echo count($tree);
print_r($tree);



Tristan, using globals for such a thing is bound to bite you in the ass at some point. IMO it is a far better idea to include the depth as a parameter to createTree. So something like:

function createTree($list, $parent, $depth=0) {
   $tree = [];
   foreach($parent as $k=>$l) {
      $l['depth'] = ($depth+1);
      if(isset($list[$l['section_id']])) {
         $child = $list[$l['section_id']])l
         $l['children'] = createTree($list, $child, $depth+1);
      }
      $tree[] = $l;
   }
}

Now you don't have to remember to set $depth to anything, it just works out of the box. Having global variables floating around just makes it easy for them to get overwritten by accident, and then you'll be wondering why the hell your menus suddenly look weird when you haven't even touched them! ;)

- Tul

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux