php - How to find Level of element from array -


i have array has id , parent_id 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 array, in inner array first element id of array , second element id of parent element.

now want find level of each element root.

assume 0 (0) root element.

you can use recursive approach. i'm assuming item @ index n in outer array has id n+1. if not, you'll first have search item matching id, otherwise rest of logic should same.

<?php function findlevel($id) {     $item = $element[$id-1];    //if assumption (above) incorrect,                                 // you'll need replace appropriate                                 // search function, simple                                 // loop through array.     $parent = $item[1];     if ($parent == 0) {         //parent root. assuming root level 0,         // item level 1.         return 1;     }     return 1 + findlevel($parent); ?> 

Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -