php - How to find Level of element from array


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.




You can use a recursive approach. I'm assuming that the item at indexN 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.

function findLevel($id) {
    $item = $element[$id-1];    //If my assumption (above) is incorrect,
                                // you'll need to replace this with an appropriate
                                // search function, which could be as simple as
                                // a loop through the array.
    $parent = $item[1];
    if ($parent == 0) {
        //Parent is root. Assuming root is level 0, then
        // this item is level 1.
        return 1;
    return 1 + findLevel($parent);



$parent_id = n;
$level = 0;
while($parent_id != 0){
   $inner_array = $element[$parent_id];
   $parent_id = $inner_array[1];
   $level ++;

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

People are also looking for solutions to the problem: php - Validating form data with Multiple inputs


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.