Quantcast
Channel: Get path from adjacency list data - Stack Overflow
Viewing all articles
Browse latest Browse all 4

Answer by viral for Get path from adjacency list data

$
0
0

Consider this array,

$input = [    ['id'=>1, 'name'=>'Anniversary', 'parent'=>0],    ['id'=>12, 'name'=>'New arrives', 'parent'=>1],    ['id'=>13, 'name'=>'Discount', 'parent'=>12],    ['id'=>6, 'name'=>'Birthday', 'parent'=>0]];

and this function,

function path($element_id, $input, $ids = []){    if(!$ids) // for performance, make this once and pass it around    {           $ids = array_column($input, 'id'); // array containing only 'id's of $input    }       $current_key = array_search($element_id, $ids); // search for $input variable's current key    unset($ids[$current_key]); // unsetting used keys to make above array search faster next time    $current_element = $input[$current_key]; // get current element as array from $input    $names[] = $current_element['name']; // create an array containing current element    if($current_element['parent'] != 0) // check if current element have parent    {           $names[] = path($current_element['parent'], $input, $ids); // call this function, let it return string, append it to $names    }       return implode('⟶', array_reverse($names)); // make final return, seprate by ⟶}

Reading echo path(13, $input); will return

Anniversary ⟶ New arrives ⟶ Discount

Here is minified version of the same function

function path($a,$b,$c=[]){if(!$c){$c=array_column($b,'id');}$d=array_search($a,$c);unset($c[$d]);$e=$b[$d];$f[]=$e['name'];if($e['parent']!=0){$f[]=path($e['parent'],$b,$c);}return implode('⟶',array_reverse($f));}

Thanks to code reviewers Loufylouf and Quill


Viewing all articles
Browse latest Browse all 4

Trending Articles