How to get parent id(root parent) from child id

Bikal Basnet picture Bikal Basnet · Nov 12, 2012 · Viewed 7.2k times · Source

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?

Answer

jmgardn2 picture jmgardn2 · Nov 12, 2012

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.