# 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(
=>array(1,0), --------level     1
=>array(2,0), -------level     1
=>array(3,1), ------level      2
=>array(4,1),  ------level     2
=>array(5,1), ------level      2
=>array(6,2), ------level      2
=>array(7,3), ------level      3
=>array(8,2), ------level      2
=>array(9,3), ------level      3
=>array(10,6), ------level     3
=>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.

781

#### Solution:

You can use a recursive approach. I'm assuming that the item at index`N` in the outer array always has id`N+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.

``````<?php
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;
if (\$parent == 0) {
//Parent is root. Assuming root is level 0, then
// this item is level 1.
return 1;
}
return 1 + findLevel(\$parent);
?>
``````
312

#### Solution:

``````\$parent_id = n;
\$level = 0;
while(\$parent_id != 0){
\$inner_array = \$element[\$parent_id];
\$parent_id = \$inner_array;
\$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

Source