我有以下数组:
Array
(
[1] => 0
[2] => 1
[3] => 2
[4] => 3
[5] => 1
[6] => 0
)
此数组的键是唯一的,并且值显示键的父级。 喜欢1&的父母6为0,2的父为1,3为2 ....
我正在写一个递归函数,它会找到给定子id的父母。 (4- GT; 3→2→1→0) 这是我的代码:但它没有返回结果
$child_node = 4;
function find_parents($child_node){
global $tree, $mark;
$mark[$child_node] = TRUE;
$ans = array(); //blank array for result
foreach($tree[$child_node]->children as $child)
if(!$mark[$child]){
$ans[$child]=$child;
find_parents($ans[$child],$child);
}
}
Heres是我如何创建树
class node {
var $children;
var $parents;
public function __construct(){
$this->children = array();
$this->parents = array();
}
}
$tree = array();
foreach ($a as $q => $p){
if(!isset($tree[$p]))
$tree[$p] = new node;
if(!isset($tree[$q]))
$tree[$q] = new node;
$mark[$p]=FALSE;
$mark[$q]=FALSE;
array_push($tree[$p]->children,$q);
}
答案 0 :(得分:1)
实际上你不需要递归函数。一个简单的循环就足够了:
这样的事情:
function find_parents($child, $tree) {
$parents = array();
while (isset($tree[$child])) {
$child = $tree[$child]; // move to the immediate parent
$parents[] = $child; // and add that parent to the list
}
return $parents;
}
然后你可以这样称呼它:
$tree = array(1 => 0, 2 => 1, 3 => 2, 4 => 3, 5 => 1, 6 => 0);
find_parents(4, $tree); // returns array(3, 2, 1, 0)
find_parents(5, $tree); // returns array(1, 0)
如果要将子项包含在返回的列表中,可以将其添加到函数开头的行中,如下所示:
$parents = array($child);