【发布时间】: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