Search code examples
phparraysiterationphp4

loop though a multi level array with an unknown amount of levels


I have a categories table that looks like this:

----------------------------------------
|  id   |  parentId  |  Name           |
----------------------------------------
   1          0         Cat 1
   2          0         Cat 2
   3          0         Cat 3
   4          2         Cat 4
   5          3         Cat 5
   6          5         Cat 6

Basically I need to iterate through the categorys creating a UL LI html list like the following:

<ul id="categories">
    <li id="1">Cat 1</li>
    <li id="2">Cat 2
       <ul>
           <li id="4">Cat 4</li>
       </ul>
    </li>
    <li id="3">Cat 3
        <ul>
           <li id="5">Cat 5
               <ul>
                   <li id="6">Cat 6</li>
               </ul>
           </li>
        </ul>
    </li>
</ul>

Im having major issues trying to iterate over this trying to create the above html. The id's maybe any number of levels deep within parentId's. Im donig this in PHP. Because there are nth number of levels deep I think I need to do some kind of array_walk funuction but not surch how. Also to make things just a little harder the machine it sists on runs PHP4 and I know it needs upgrading but it cant at the min so I need a php 4 solution ideally. How should I go about doing this?


Solution

  • Try the left/right tree method for storing hierarchical information in a database.

    http://blogs.sitepoint.com/hierarchical-data-database/

    This is what I do in my website, where I have multi-level LIs that need to open at 1:6 and have children 2:3,4:5 where the first number is the 'left' and the second is the 'right'. I have about 5 levels deep at the moment, but you could have many more. It's just a matter of developing an interface for setting the correct left/right values based on the position you add it to.

    You just have to add a 'lft' and 'rgt' column to your table (as explained in that article).

    enter image description here