php - Get path from adjacency list data -


i have array (data adjacency table) , looks like:

array (     [0] => array         (             [id] => 1             [name] => anniversary             [parent] => 0         )      [1] => array         (             [id] => 12             [name] => new arrives             [parent] => 1         )      [2] => array         (             [id] => 13             [name] => discount             [parent] => 12         )      [3] => array         (             [id] => 6             [name] => birthday             [parent] => 0         ) ) 

and i'm looking way retrieve path id;

for example: getpath(13): anniversary->new arrives->discount; example: getpath(12): anniversary->new arrives; example: getpath(1): anniversary; example: getpath(6): birthday; 

how can this? thanks!

function getpath($id, $arr, $level = 0) {     $result = array();     foreach($arr $key => $value){         if($id == $value['id']){             $result[] = $value['name'];             $id = $value['parent'];             if($id != 0){               $result = array_merge($result, getpath($id, $arr, $level+1));             }else{                 break;             }         }     }     return $level ? $result : implode('->',array_reverse($result)); } echo getpath(13,$arr); 

Comments

Popular posts from this blog

How has firefox/gecko HTML+CSS rendering changed in version 38? -

android - CollapsingToolbarLayout: position the ExpandedText programmatically -

Listeners to visualise results of load test in JMeter -