给出以下数组:
array(..) {
[1111]=>
&array(3) {
["category_id"]=>
int(1111)
["parent_id"]=>
int(0)
["children"]=>
array(2) {
[2222]=>
&array(3) {
["category_id"]=>
int(2222)
["parent_id"]=>
int(1111)
["children"]=>
array(2) {
[5555]=>
&array(1) {
["category_id"]=>
int(5555)
["parent_id"]=>
int(2222)
}
}
[3333]=>
&array(2) {
["category_id"]=>
int(3333)
["parent_id"]=>
int(1111)
}
}
假设数组深度未知,我如何确定父节点的路径?
例如,对于category_id = 5555
,我应该得到以下结果:0, 1111,2222
。对于category_id = 3333
,它将是0,1111
答案 0 :(得分:1)
一种方法:
function findParent($node, $array, &$parents) {
if (array_key_exists($node, $array)) {
$parents[] = $array[$node]['parent_id'];
}
else {
foreach ($array as $item) {
if (array_key_exists('children', $item)) {
$parents[] = $item['parent_id'];
findParent($node, $item['children'], $parents);
}
}
}
}
findParent(5555, $A, $parents);