At some point of my coding, I need to build ‘menu – submenu’ or a tree from my database query result. I’m facing this problem a couple of week before and found its hard to achieved it. I have tried the if else statement and foreach loop but failed. After hours of googling, I found that we can use recursive function to build a tree.  Here is my solution.

This is the original array:

This is what we want to achieved:

We can use recursive function to achieved this.