【问题标题】:Flat Array into tree structure issue平面数组成树结构问题
【发布时间】:2013-07-22 07:54:48
【问题描述】:

我有以下数组:

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

此数组的键是唯一的,并且值显示键的父级。 就像 1 和 6 的父级是 0,2 的父级是 1,因为 3 是 2....

我正在编写一个递归函数,它将找到给定孩子 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);

}

【问题讨论】:

  • 然后呢?你遇到了什么问题?
  • 它没有给我子节点 4 的父节点
  • 我不完全清楚您要做什么,并且您上面的代码不完整(缺少函数结尾,没有返回等)如果您只是想得到来自原始数组的父母列表,实际上不需要递归。请参阅我的答案以获得解决方案,或提供更多说明。

标签: php arrays multidimensional-array


【解决方案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);

【讨论】:

  • 我得到了一个父数组为空的对象
  • 我不确定你的意思 - 这段代码中根本没有对象。您是否将它与您的原始代码混合在一起,也许?此函数直接对原始数组进行操作,而不是对任何树对象。
  • 是的,我想我正在混合它,如何与树对象一起使用?我想稍后爬树并找到节点
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-01-22
  • 2017-07-19
  • 2021-04-19
  • 1970-01-01
  • 2015-11-08
  • 1970-01-01
  • 2015-12-13
相关资源
最近更新 更多