Skip to content
Advertisement

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));

enter image description here

and my desired output is, I give input the child node Id and It will return all the parents. for example I will give child ID ‘raja’ and It will give output 1) manish 2) vijay 3) admin.

Advertisement

Answer

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 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.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement