I imagine this is a fairly common requirement for people when it comes to building any kind of application that relies on sorting and displaying data in categories – any CMS/Forums/Carts etc and I’ve been tearing my hair out trying to think of a way to show all categories and their children to no avail – the best I’ve managed is while loop within while loop (however many levels I think I may require) but this defeats the point of programming in my opinion, it needs to be effortlessly extensible.
So, given:
Category 1
-Sub cat
-Sub cat
--Sub sub cat
--- Sub sub cat
-- Sub sub cat
-Sub cat
Category 2
-Sub cat
-Sub cat
--Sub sub cat
---sub sub sub cat
----sub sub sub sub cat
-sub cat
Category 3
-Sub cat
Database fields: ID Name ParentIDS
How would you go about echoing each of the categories in their hierarchy from a database?
I’d post my code, but obviously its massive, given the long-hand way of nesting loops.
I’ve thought about writing bits of code that find the ‘depth’ of the category tree but that still isn’t cutting it.. ideas?
The structure you’re talking about is essentially a tree. Iterating over a tree is relatively simple if you use recursion. I don’t know what database access code you’re using, but you should be able to extrapolate accordingly from the following psuedocode:
In english, that means print an item in the list, then print its children, and once all children (and their children) have printed, move on to the next item in the list.