简体   繁体   English

如何使用 php 从子 ID 获取顶级父 ID?

[英]How to get top parent id from a child id using php?

I am an amateur in PHP.我是 PHP 的业余爱好者。 I tried a lot of suggestions from here but I didn't get the result I need.我从这里尝试了很多建议,但没有得到我需要的结果。 I want to get the top parent id of a child.我想获得孩子的最高父母ID。 ex.前任。 For id=10 top parent is 8. This is the array I get from the database.对于 id=10,top parent 是 8。这是我从数据库中得到的数组。 Thanks in advance.提前致谢。

$events = mysqli_query($dbtmx,"SELECT * FROM tmetrix_events WHERE status='1'");
while($re=mysqli_fetch_assoc($events)){
  $array[] = array('id'=>$re['id'],'parent_id'=>$re['parent_id']);
}

And the array I am receiving is我收到的数组是

Array
(
    [0] => Array
        (
            [id] => 5
            [parent_id] => 0
        )

    [1] => Array
        (
            [id] => 6
            [parent_id] => 5
        )

    [2] => Array
        (
            [id] => 7
            [parent_id] => 5
        )

    [3] => Array
        (
            [id] => 8
            [parent_id] => 0
        )

    [4] => Array
        (
            [id] => 9
            [parent_id] => 8
        )

    [5] => Array
        (
            [id] => 10
            [parent_id] => 9
        )

)

Now I want to find the top parent or root parent id of the child.现在我想找到孩子的顶级父母或根父母ID。

I tried Steverst1 and AymDev's code.我尝试了 Steverst1 和 AymDev 的代码。 But I am getting the result.但我得到了结果。

You can create a recursive function which will run through all parents until it finds 0 which I assume means there is no parent:您可以创建一个递归 function 它将遍历所有父母,直到找到0我认为这意味着没有父母:

function get_top_parent(int $id, array $list): ?array
{
    // Find current item
    $key = array_search($id, array_column($list, 'id'));
    $item = $list[$key] ?? null;
    
    // Check if item has parent
    if (null !== $item && $item['parent_id'] !== 0) {
        // recursive call
        return get_top_parent($item['parent_id'], $list);
    }
    
    // No parent (or no item)
    return $item;
}

Tested on 3v4l.org : https://3v4l.org/PPm3K3v4l.org上测试: https://3v4l.org/PPm3K

Assumption that 0 in parent_id means that it is the parent we are looking for.假设parent_id中的 0 表示它是我们正在寻找的父级。 So get the id of it.所以得到它的id。

$child_id = 10;
$parent = 0;
while ($child_id != 0) {
    foreach ($array as $key => $inner_arr) {
        $id = $inner_arr['id'];
        $parent_id = $inner_arr['parent_id'];
        if($id === $child_id){
            $child_id = $parent_id;
            $parent = $id;
        }
    }
}
echo $parent; // 8

Demo演示

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

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