Problem with recursively get out tree

Discussion in 'PHP' started by kustov, Jul 6, 2007.

  1. #1
    I have a such array:
    $tree= array(
    0=>array('id'=>1, 'parent'=>0),
    1=>array('id'=>2, 'parent'=>0),
    2=>array('id'=>3, 'parent'=>2),
    3=>array('id'=>4, 'parent'=>3),
    4=>array('id'=>5, 'parent'=>2),
    5=>array('id'=>6, 'parent'=>0),
    6=>array('id'=>7, 'parent'=>3),
    7=>array('id'=>8, 'parent'=>4),
    8=>array('id'=>9, 'parent'=>1),
    9=>array('id'=>10, 'parent'=>0),
    10=>array('id'=>11, 'parent'=>10),
    );
    Code (markup):
    and need to get this output:
    -1
    --9
    -2
    --3
    ---4
    ----8
    --5
    --7
    -6
    -10
    --11
    But I'm very bad in recursion:eek:, please help !
     
    kustov, Jul 6, 2007 IP
  2. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #2
    
    foreach ($tree AS $item)
    {
    	echo "ID: {$item['id']}<br />\n";
    	echo "Parent {$item['parent']}<br />\n";
    }
    
    PHP:
     
    nico_swd, Jul 6, 2007 IP
  3. ma0

    ma0 Peon

    Messages:
    218
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Uh? nico, have you read what he asked?

    kustov, I think you need to rething everything, because your tree is a mess (IMHO).

    You should loop through all the element a lot of times to build that.
    Anyway look at what I wrote down here. I'm not sure it works, but I'm sure it will give you enough hints to help you find the right solution for your problems.
    Note that it is slow if you have lots of elements.

    printelement($tree,$tree[0]);

    function printelement($tree,$item){
    foreach($tree as $it2){
    if ($it2['parent']==$item['id'])
    echo $it2['id'];
    printelement($tree,$it2);
    }
    }
     
    ma0, Jul 6, 2007 IP
  4. robi-bobi

    robi-bobi Peon

    Messages:
    19
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #4
    true

    I suggest having array that will look more like this:
    
    $tree = array(
      0 => array (
        'id'=>1, 
        'name'=>'first one',
        'children'=> array (
          0 => array (
            'id'=>8, 
            'name'=>'8. item',        
          )
        ),
      ),
      1 => .....
    
    PHP:
    however, if you are building the tree dynamically and it is small and is not very 'deep' - it is acceptable to use the structure you are using now

    another advice: use caching

    edit:
    ma0's function should do the job
    in case you need indentation, use another third param, to tell to your function how 'deep' into the tree you are. then when printing the name, also print indentation char ('-' in your example) N times (where N is the third param)
     
    robi-bobi, Jul 6, 2007 IP