I have an array (data from adjacency table) and it looks like:
$data = 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
)
)
I have a function that return path array by id:
function categoryRecursion($element, $input) {
$return = array_filter($input, function($v) use ($element) { return $v->id == $element; });
$last = end($return);
$str[] = $last;
if($last->parent !=0) {
$str[] = categoryRecursion($last->parent, $input);
}
return array_reverse($str); //implode('->',array_reverse($str));
}
When I use it:
print(categoryRecursion('13',$data));
I'm getting this output:
Array
(
[0] => Array
(
[0] => Array
(
[0] => stdClass Object
(
[id] => 1
[name] => Anniversary
[parent] => 0
)
)
[1] => stdClass Object
(
[id] => 12
[name] => New arrives
[parent] => 1
)
)
[1] => stdClass Object
(
[id] => 13
[name] => Discount
[parent] => 12
)
)
But I'm looking for the way to get output:
Array
(
[0] => stdClass Object
(
[id] => 1
[name] => Anniversary
[parent] => 0
)
)
[1] => stdClass Object
(
[id] => 12
[name] => New arrives
[parent] => 1
)
)
[2] => stdClass Object
(
[id] => 13
[name] => Discount
[parent] => 12
)
)
How can I fix my function?
I don't understand where your array becomes object. If work with array, the code can be