[prev in list] [next in list] [prev in thread] [next in thread] 

List:       php-general
Subject:    [PHP] nested tree
From:       Daniel Demacek <carpefore () yahoo ! com>
Date:       2003-10-31 8:38:57
[Download RAW message or body]

Hi all,

I have a sorted associative array that represents
nested tree in the form of (note: parent=0 is the top
level):

$ar[0]['id']=1;
$ar[0]['parent_id']=0;
$ar[0]['name'] = 'john';

$ar[1]['id']=4;
$ar[1]['parent_id']=1;
$ar[1]['name'] = 'mary';

$ar[2]['id']=7;
$ar[2]['parent_id']=1;
$ar[2]['name'] = 'jane';

$ar[3]['id']=2;
$ar[3]['parent_id']=1;
$ar[3]['name'] = 'joe';

$ar[4]['id']=23;
$ar[4]['parent_id']=1;
$ar[4]['name'] = 'tim';

$ar[5]['id']=11;
$ar[5]['parent_id']=23;
$ar[5]['name'] = 'martin';

$ar[6]['id']=9;
$ar[6]['parent_id']=11;
$ar[6]['name'] = 'zoe';

$ar[7]['id']=6;
$ar[7]['parent_id']=9;
$ar[7]['name'] = 'pete';

$ar[8]['id']=12;
$ar[8]['parent_id']=1;
$ar[8]['name'] = 'oscar';

Now I have written the following code to represent
this nested tree using <ul> and </ul> in html, which I
think is very ugly and probably not very efficient, I
was wondering if there was a better solution, maybe
more efficient:

$l=0;
$out='';
$level = array();

for($i=0; $i<count($ar); $i++)
{
     # if top level close all unopened <ul>s.
     if($ar[$i]['parent_id'] == 0)
     {
         for($m=0; $m<$l; $m++)
         {
                 $out .= '</ul>';
         }
         $l=0;
     }
     
     $out .= $ar[$i]['name'].' l:'.$l.'<br>';

     if( $ar[$i]['id'] ==  $ar[$i+1]['parent_id'])
     {
          $out .= '<ul>';

          $level[ $ar[$i]['id'] ] = $l;

          $l++;
     }
     else
     {
          if($l && $ar[$i]['parent_id'] !=
$ar[$i+1]['parent_id'])
          {
               $number = $l - $level[
$ar[$i+1]['parent_id'] ];
               for($v=0; $v<$number-1; $v++)
               {
                    $out .= '</ul>';
                    $l--;
               }

          }
     }
     # if we are at the end close all opened <ul>s.
     if(!$ar[$i+1]['id'])
     {
          for($m=0; $m<$l; $m++)
          {
               $out .= '</ul>';
          }

     }
}

echo '<pre>';
echo $out;


Thanks, Dan.






__________________________________
Do you Yahoo!?
Exclusive Video Premiere - Britney Spears
http://launch.yahoo.com/promos/britneyspears/

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

[prev in list] [next in list] [prev in thread] [next in thread] 

Configure | About | News | Add a list | Sponsored by KoreLogic