How to get parent id(root parent) from child id [duplicate]

对着背影说爱祢 提交于 2019-12-10 23:18:53

问题


Possible Duplicate:
function returning only once, why?

my Database structure looks like

id|parent|
1 |   0  |
2 |   0  |
3 |   0  |
4 |   1  |
5 |   4  |
6 |   5  |

I am in need of a function that gets parent(i.e parent=0) for a id as parameter For eg .. get_parent(6)==returns 1 I did some research and found this question

How can I recursively obtain the "parent ID" of rows in this MySQL table?

I tried making this function

    function get_parent_id($cid,$found=array())
    {
     array_push($found,$cid);
     $sql="SELECT * FROM tbl_destinations WHERE id=$cid";
     $result = mysql_query($sql) or die ($sql);
     if(mysql_num_rows($result))
     {

        while($row = mysql_fetch_assoc($result))
        {
        $found[] = get_parent_id($row['parent'], $found);
        }
     }
return $found;
       }

I make a call by

$fnd=get_parent_id();
$array_reverse($fnd);
$parent_root=$fnd['0'];

But my method is wrong. Where did I go wrong?


回答1:


Are you trying to get the parent ID within the SQL query, or using PHP? If you're looking at using PHP for it, you could either do $arr[6]['parent'] assuming you got the information from the database into an array. Or, you could have a function:

<?php
//Let's assume you have your data from the database as such
$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));

function get_key($arr, $id)
{
    foreach ($arr as $key => $val) {
        if ($val['id'] === $id) {
            return $key;
        }
    }
    return null;
}

function get_parent($arr, $id)
{
    $key = get_key($arr, $id);
    if ($arr[$key]['parent'] == 0)
    {
        return $id;
    }
    else 
    {
        return get_parent($arr, $arr[$key]['parent']);
    }
}

echo get_parent($arr, 6);
?>

Note that the code is untested, and just a sample.



来源:https://stackoverflow.com/questions/13349877/how-to-get-parent-idroot-parent-from-child-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!