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

From: Date: Mon, 20 Aug 2012 12:54:45 +0000
Subject: Re: Display Array Tree as Menu - Can't figure out how to finddepth with something over 2 levels : ANSWERED
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-318778@lists.php.net to get a copy of this message
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

« previous php.general (#318778) next »