I came through a question on Stack Overflow, which shows this array structure:
array (size=4)
0 =>
array (size=3)
'id' => int 1
'name' => string 'Anniversary' (length=11)
'parent' => int 0
1 =>
array (size=3)
'id' => int 12
'name' => string 'New arrives' (length=11)
'parent' => int 1
2 =>
array (size=3)
'id' => int 13
'name' => string 'Discount' (length=8)
'parent' => int 12
3 =>
array (size=3)
'id' => int 6
'name' => string 'Birthday' (length=8)
'parent' => int 0
and the required outcome needs to be the path for that list like shown below, implementation of adjacency list:
13 - Anniversary->New arrives->Discount 12 - Anniversary->New arrives 1 - Anniversary 6 - Birthday
I came to this solution:
$in = [
['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 ]
];
function path($element, $input) {
$return = $input[ array_search($element, array_column($input, 'id')) ];
$str [] = $return ['name'];
if($return ['parent'] != 0) {
$str [] = path($return ['parent'], $input);
}
return implode('->', array_reverse($str));
}
var_dump(path(13,$in));
It gets the task done, but I want to know if any improvements can be made to optimize the approach to the problem.