Loop Structure

Discussion in 'Programming' started by Cozmic, Jul 25, 2010.

  1. #1
    Hey,

    I am trying to figure out how to structure a set of loops which will display the sub levels of several items to an infinite depth. I hate a database filled with items. Each item can have a "sub item". The ID of the parent is stored in the sub item. I want to loop through all of the "super items", then display all of their sub items and all of their sub items sub items. Let's say, for example, I had this:

    
    - Super Item
       - Sub
           - Sub
               - Sub
               - Sub
               - Sub
           - Sub
    -Super Item
       - Sub
    
    Code (markup):
    And so on. So, what I need is pseudocode or PHP code which shows how one would set up a loop to go through all of these items, assuming I had them stored in the database like this:

    
    id                 parent
    1                  -       
    2                  1
    3                  2
    4                  2
    5                  3
    6                  5
    
    Code (markup):
     
    Cozmic, Jul 25, 2010 IP
  2. Deacalion

    Deacalion Peon

    Messages:
    438
    Likes Received:
    11
    Best Answers:
    0
    Trophy Points:
    0
    #2
    By the sounds of your problem I don't think it's loops you require, but a recursive function.
     
    Deacalion, Jul 25, 2010 IP
  3. Deacalion

    Deacalion Peon

    Messages:
    438
    Likes Received:
    11
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Since I'm on my lunch break, I coded up an example:
    
    <?php
    showAllItems();
    
    function showAllItems($parent = 0, $space = '') {
        $query = mysql_query('SELECT name, id FROM items WHERE parent = "'.$parent.'"'); 
        
        while ($row = mysql_fetch_assoc($query)) {
            echo $space . '- ' . $row['name'] . "\n";   
            showAllItems($row['id'], $space . "\t");
        }
    }
    ?>
    
    PHP:
     
    Deacalion, Jul 25, 2010 IP
  4. Cozmic

    Cozmic Member

    Messages:
    146
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    48
    #4
    Hmm, looks like that's a lot simpler than how I thought it would be. I tested it and it works fine. Thanks! I'll post again if I see any problems with it, but I think it will do.
     
    Cozmic, Jul 25, 2010 IP