Skip to content
Advertisement

Create Tree Structure from Array in PHP

I have an array like this:

JavaScript

Now I need some efficient way to convert this into tree structure like this.

JavaScript

I no need to add them left or right, I just need the simple levels that I will pass to jQgrid.

Advertisement

Answer

Collect all ids in the order of parent -> child in an array where parent_id is the key and it has an array of all child IDs. Second step is to just traverse the tree and assign the ranks.

JavaScript

Online Demo

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement