[英]get parent nodes from a node tree array
[
{
"id": 1573695284631,
"name": "Cars",
"pid": 0,
"children": [
{
"id": 1573695292010,
"name": "Audi",
"pid": 1573695284631
},
{
"id": 1573695305619,
"name": "BMW",
"pid": 1573695284631,
"children": [
{
"id": 1573695328137,
"name": "3 Series",
"pid": 1573695305619
},
{
"id": 1573695335102,
"name": "X5",
"pid": 1573695305619
}
]
}
]
},
{
"id": 1573695348647,
"name": "Motorcycles",
"pid": 0,
"children": [
{
"id": 1573695355619,
"name": "Ducatti",
"pid": 1573695348647
}
]
}
]
假设我在 PHP 中有这个类似节点树的数组(为了便于阅读,上面在 json 中表示)。 对于给定的子节点 ID,我想找到它嵌套的所有父节点 ID。 例如,
getParentNodes($haystack, $child_node_id=1573695328137); //[1573695284631, 1573695292010, 1573695305619]
我认为这是递归的用例。 这是我最好的尝试:
function getParentNodes($haystack, $child_node_id) {
if( empty($haystack->children) )
return;
foreach($haystack->children as $child) {
if($child->id == $child_node_id) {
// $child found, now recursively get parents
} else {
getParentNodes($child, $child_node_id);
}
}
}
您缺少返回结果。 这就是你想要的。
function getParentNodes($arr, $child_node_id) {
$result = [];
foreach($arr as $item) {
if($item->pid == $child_node_id) {
$result[] = $item->id;
}
if(!empty($item->children)) {
$result[] = getParentNodes($item->children, $child_node_id);
}
}
return $result;
}
您还需要将值作为平面数组
$values = getParentNodes($values, 1573695284631);
// do flat arr
array_walk_recursive($values,function($v) use (&$result){ $result[] = $v; });
// your values
var_dump($result);
实际上你有一个pid
属性,我认为它是父 id。 所以你可以得到这样的父母。
function getParentNodes($haystack, $child_node_id, $parent = null) {
if(!property_exists($haystack, 'children')) return;
foreach($haystack->children as $child){
if(property_exists($child, 'children')){
return getParentNodes($child, $child_node_id, $haystack);
}
if($child->id == $child_node_id){
return $haystack->pid . ' => ' . $haystack->id . ' => ' . $child->id;
}
}
}
就这样称呼吧。
print_r(getParentNodes($haystack, 1573695328137));
Output 是。
1573695284631 => 1573695305619 => 1573695328137
我最终写了 2 个递归函数
function treeSearch($needle, $haystack) {
foreach($haystack as $node) {
if($node->id == $needle) {
return $node;
} elseif ( isset($node->children) ) {
$result = treeSearch($needle, $node->children);
if ($result !== false){
return $result;
}
}
}
return false;
}
treeSearch 会在树中找到节点,然后我需要递归 go 直到父 id (pid) 为 0
function getParents($node, $hierarchy, $all_parent_ids=[]) {
if($node->pid != 0) {
$parent_node = treeSearch($node->pid, $hierarchy);
$all_parent_ids[] = $parent_node->id;
$result = getParents($parent_node, $hierarchy, $all_parent_ids);
if ($result !== false){
return $result;
}
}
return $all_parent_ids;
}
然后,假设树被称为 $tree 我可以这样称呼它们:
$node = treeSearch(1573695328137, $tree);
$parents = getParents($node, $tree);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.