php - How to find Level of element from array
72
I have an array which has id and parent_id like this
$element=new array(
[0]=>array(1,0), --------level 1
[1]=>array(2,0), -------level 1
[2]=>array(3,1), ------level 2
[3]=>array(4,1), ------level 2
[4]=>array(5,1), ------level 2
[5]=>array(6,2), ------level 2
[6]=>array(7,3), ------level 3
[7]=>array(8,2), ------level 2
[8]=>array(9,3), ------level 3
[9]=>array(10,6), ------level 3
[10]=>array(11,6), ------level 3
);
this is my array, in inner array first element is id of the array and second element is id of parent element.
now i want to find level of each element from root.
assume zero (0) is root element.
Answer
Solution:
You can use a recursive approach. I'm assuming that the item at index
N
in the outer array always has idN+1
. If not, you'll first have to search for the item with the matching id, but otherwise the rest of the logic should be the same.Answer
Solution:
Let's try this, you initially set $parent_id to the index of the $element array you want to know the level. Make sure each level can be calculated