我遇到递归搜索问题。这个递归函数将对象导航到第一个叶子,似乎忽略了递归。
$node = $this->_find_recursive($staff, "user_id", 681); // $staff is the json_decoded of "Source Data" (see below)
这应返回“James Anderson”节点,因为它具有user_id = 681但该函数从未到达该节点。这有什么不对?我将感谢你的帮助。谢谢!
root 0 681
公司0 681
超级用户670 681
迈克尔史密斯671 681
克里斯托弗约翰逊672 681
private function _find_recursive($node, $key, $value)
{
echo " ". " ". $node->name. " ". $node->$key. " ". $value . "\n";
if($node->$key == $value)
{
return $node;
}
else
{
foreach($node->children as $cur_node)
{
return $this->_find_recursive($cur_node, $key, $value);
}
}
return NULL;
}
{
"text": ".",
"name": "root",
"user_id": 0,
"children": [
{
"user_id": 0,
"name": "Company",
"staff_profile" : "company",
"children": [
{
"user_id": 670,
"name": "Super User",
"staff_profile" : "ceo",
"children": [
{
"user_id": 671,
"name": "Michael Smith",
"staff_profile" : "manager",
"children": [
{
"user_id": 672,
"name": "Christopher Johnson",
"staff_profile" : "representative",
"children": []
},{
"user_id": 675,
"name": "Daniel Brown",
"staff_profile" : "representative",
"children": []
}
]
},
{
"user_id": 676,
"name": "David Davis",
"staff_profile" : "manager",
"children": [
{
"user_id": 677,
"name": "Andrew Miller",
"staff_profile" : "representative",
"children": []
},{
"user_id": 678,
"name": "Justin Wilson",
"staff_profile" : "representative",
"children": []
}
]
}
]
},
{
"user_id": 681,
"name": "James Anderson",
"staff_profile" : "ceo",
"children": [
{
"user_id": 682,
"name": "Nicholas Tomas",
"staff_profile" : "manager",
"children": [
{
"user_id": 683,
"name": "Joseph Jackson",
"staff_profile" : "representative",
"children": []
}
]
},
{
"user_id": 687,
"name": "Kyle Thompson",
"staff_profile" : "manager",
"children": [
{
"user_id": 688,
"name": "Brandon Garcia",
"staff_profile" : "representative",
"children": []
}
]
}
]
}
]
}
]
}
答案 0 :(得分:0)
return
循环中未选中的foreach
是问题所在。你基本上是在第一次迭代时退出循环。试试这个......
foreach($node->children as $cur_node) {
if ($check = $this->_find_recursive($cur_node, $key, $value)) {
return $check;
}
}