我有一个数组(来自邻接表的数据),它看起来像:
$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
)
)
我有一个按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));
}
当我使用它时:
print(categoryRecursion('13',$data));
我得到了这个输出:
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
)
)
但我正在寻找获得输出的方法:
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
)
)
如何修复我的功能?
答案 0 :(得分:0)
我不明白你的数组在哪里成为对象。如果使用数组,代码可以是
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 = array_merge(categoryRecursion($last['parent'], $input), $str);
}
return $str;
}