扁平数组进入树结构问题


Flat Array into tree structure issue

我有以下数组:

Array
(
    [1] => 0
    [2] => 1
    [3] => 2
    [4] => 3
    [5] => 1
    [6] => 0
)

此数组的键是唯一的,并且值显示键的父级。像1&6是0,2的父项是1,对于3是2…

我正在写一个递归函数,它将为给定的子id找到父id。(4->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);
        }
     }

以下是我如何创建树

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);
}

实际上不需要递归函数。一个简单的循环就足够了:

类似这样的东西:

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);