learn

Build Hierarchy Array

category: Snippets
Created by: Assaad Youssef Abou-Rached

Build Hierarchy Array

category: Snippets
Created by: Assaad Youssef Abou-Rached
twitter google+ facebook pin 

Build Hierarchy Array

The function is pretty simple and straight-forward yet powerful: you provide it with an array of unsorted data, and it will append the children to their root element.

How to use this function in real applications?

Say that you have the following table in your database

Cat_ID Cat_Name Parent_ID
1 Electronics 0
2 Kitchen Tools 0
3 Mobiles 1
4 TVs 1
5 Microwave 2
6 Smart Phones 3

You want to pull the data from the table and display the children rows under parent rows.

Parent id must be written as Parent_ID, and element id must be written as Self_ID. If you want to change these terms, then you will have to edit the function's code and replace Parent_ID and Self_ID with whatever that suits you. All children elements will be under "children" (you can replace that too)
The code won't work here, it is just for explanatory reasons.