I have a sample MySQL table with the columns ID, NAME AND ID_PARENT.
ID | NAME | ID_PARENT |
---|---|---|
1 | NODE 1 | NULL |
2 | NODE 2 | 1 |
3 | NODE 3 | 2 |
4 | NODE 4 | 2 |
5 | NODE 5 | 1 |
6 | NODE 6 | 5 |
7 | NODE 7 | 6 |
8 | NODE 8 | 7 |
9 | NODE 9 | 6 |
10 | NODE 10 | 5 |
11 | NODE 11 | NULL |
12 | NODE 12 | 11 |
13 | NODE 13 | 11 |
14 | NODE 14 | 13 |
18 | NODE 15 | 14 |
And I have the following tree based on the above data and I need to fetch a node/tree/hierarchy based on ID provided.
NODE 1
NODE 2
NODE 3
NODE 4
NODE 5
NODE 6
NODE 7
NODE 8
NODE 9
NODE 10
NODE 11
NODE 12
NODE 13
NODE 14
NODE 15
Now if I provide ID=6 (NODE 6) then we should have all the PARENTS (with their CHILDREN) of NODE 6 plus all the nested CHILDREN of NODE 6. So, we should have NODES from 1 to 10 as they fall under one PARENT NODE 1. The extracted tree would be.
NODE 1
NODE 2
NODE 3
NODE 4
NODE 5
NODE 6
NODE 7
NODE 8
NODE 9
NODE 10
So, how can we achieve the above-mentioned scenario?
NOTE: I am using PHP 7 and MySQL 5.6.