从邻接表数据数组中获取路径数组
Posted
技术标签:
【中文标题】从邻接表数据数组中获取路径数组【英文标题】:Get path array from adjacency list data array 【发布时间】:2015-06-25 16:02:05 【问题描述】:我有一个数组(来自邻接表的数据),它看起来像:
$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
)
)
如何修复我的功能?
【问题讨论】:
【参考方案1】:我不明白你的数组在哪里变成了对象。如果使用数组,代码可以是
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;
【讨论】:
以上是关于从邻接表数据数组中获取路径数组的主要内容,如果未能解决你的问题,请参考以下文章