简体   繁体   English

php 树获取子节点所有父节点的列表

[英]php tree get list of all parents of child node

I want a list of all parents of the child node.我想要一个子节点的所有父节点的列表。 I am searching but I am getting all child nodes of the parent.我正在搜索,但我正在获取父节点的所有子节点。 my array look like我的数组看起来像

array(
array('id' => 1, 'parent' => 0),
array('id' => 2, 'parent' => 0),
array('id' => 3, 'parent' => 0),
array('id' => 4, 'parent' => 1),
array('id' => 5, 'parent' => 4),
array('id' => 6, 'parent' => 5));

在此处输入图像描述

and my desired output is, I give input the child node Id and It will return all the parents.而我想要的 output 是,我输入子节点 ID,它将返回所有父节点。 for example I will give child ID 'raja' and It will give output 1) manish 2) vijay 3) admin.例如,我会给孩子 ID 'raja',它会给 output 1) manish 2) vijay 3) admin。

Have a look at this example, let me know if this is what you are looking for.看看这个例子,让我知道这是否是你要找的。

<?php 
$arr = array(
    array('id' => 1, 'parent' => 0),
    array('id' => 2, 'parent' => 0),
    array('id' => 3, 'parent' => 0),
    array('id' => 4, 'parent' => 1),
    array('id' => 5, 'parent' => 4),
    array('id' => 6, 'parent' => 5));

$parents = [];
function find_parents($input, $id) {
    global $parents, $arr;
    if(is_array($input)) {
        foreach($input as $k => $val) {
           
            if($val['id'] == $id  && $val['parent'] != 0) {
                array_push($parents, $val['parent']);
                find_parents($arr, $val['parent']);
            }
        }
    }
}
find_parents($arr, 6);
print_r($parents);

Giving 6 as input will output6作为输入将 output

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

You can use recursion so that it can be used up to any level.您可以使用递归,以便它可以用于任何级别。 No need to limit the levels.无需限制级别。

                find_parents($arr, $val['parent']);

In Above line, instead of $arr in recursive argument, it should be $input array variable.在上面的行中,而不是递归参数中的 $arr,它应该是 $input 数组变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM