PHP make tree-structured array from 4 arrays

Viewed 146

I have on a page categories (represented as checkboxes). On the next page I have subcategories of categories from 1st page. On the next page sub-categories for elements in the 2nd page and so on. I save all the selected items in arrays representing the choices made in different levels.The problem is that I don't know how to make a tree structure from all these arrays. Let me say what I have at the moment:

I have 4 arrays, lets imagine them as 4 levels (each level represents checkboxes selected on the # page). I keep in them the checkboxes selected by the user. Here is an example of data: (the value represents the id of the item in the database)

The l1 value of $_SESSION['0'] is '1' 

The l2 value of $_SESSION['0'] is '2' 
The l2 value of $_SESSION['1'] is '3' 

The l3 value of $_SESSION['0'] is '3' 
The l3 value of $_SESSION['1'] is '4' 
The l3 value of $_SESSION['2'] is '5' 
The l3 value of $_SESSION['3'] is '6' 

The l4 value of $_SESSION['0'] is '1' 
The l4 value of $_SESSION['1'] is '2' 
The l4 value of $_SESSION['2'] is '3' 
The l4 value of $_SESSION['3'] is '4' 
The l4 value of $_SESSION['4'] is '5' 

For each id in the database I have the id of the item it belongs to (for eg: level 2: )

id=1; name = programming, category_id = 1;

I can find the relationships by querying the database.

in the case above the both elements from l2 are subcategories of l1[0]. First 2 elements from level 3 are subcategories of l2[0] and last 2 elements are subcategories of l2[1], and in level 4 some of them are subcategories of something in level 3 (not every element may have subcategories).

How can I build the tree-structured JSON for all this data? Any ideas or suggestions? Thank you!

1 Answers
Related