Display unlimited category structure & # 8594; Subcategory & # 8594; etc.?

I assume this is a fairly common requirement for people when it comes to creating any application that uses sorting and displaying data in categories - any CMS / Forums / Carts, etc., and I tore my hair, trying to think about how to show all categories and their children to no avail - the best I have succeeded in is the while loop in the loop (although many levels, in my opinion, I can require), but this, in my opinion, is detrimental to programming. to be easily extensible.

So, considering:

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: ParentIDS ID Name

How would you choose to echo each category in your hierarchy from the database?

, , , , .

, "" , . ?

+3
3

, , . , . , , psuedocode:

function iterate_tree(arr) {
    foreach (item in arr) {
        print item;
        iterate_tree(item.children);
    }
}

- , , ( ) , .

+1
+1

as a hint, you can use Recursion. A general idea is available at http://en.wikipedia.org/wiki/Recursion . That is, you record a function that captures and displays all files and folders in the current folder. Then you reapply the same function for each subfolder in the same recursion loop. Etc etc. Etc.

+1
source

All Articles