在自循环函数php中查找父类别

Find the top category in tree structure, i am using this

echo getTopCategory($category_id); exit; // returning empty value



function getTopCategory($catid) {

    $CI = & get_instance();
    $CI->db->select('*');
    $CI->db->from('categories');
    $CI->db->where('id', $catid);
    $query = $CI->db->get();
    $result = $query->row();
    //return $catid; // for testing return working
    if($result->parent_id==0){
        //echo $catid -- working result 350
        return $catid; // root parent, not successfully returning the result
    }else{
        getTopCategory($result->parent_id);
    }

}

if i use echo inside the getTopCategory($catid) it correctly giving the parent category id but it not returning date to getTopCategory($category_id);

Return it then, see my comment in the code:

echo getTopCategory($category_id); exit; // returning empty value



function getTopCategory($catid) {

    $CI = & get_instance();
    $CI->db->select('*');
    $CI->db->from('categories');
    $CI->db->where('id', $catid);
    $query = $CI->db->get();
    $result = $query->row();
    //return $catid; // for testing return working
    if($result->parent_id==0){
        //echo $catid -- working result 350
        return $catid; // root parent 
    }else{
        //Ive added a return here
        return getTopCategory($result->parent_id);
    }

}

When you do a recursive call, you need to return the value from the recursive call itself, so it can bubble all the way back to your echo command.

You have to return the recursive function inside of your else block:

    // ...
} else {
    return getTopCategory($result->parent_id);
}

You should return in else as well because if the condition goes to else then it calls itself and has the return value but does not return it in the first place.

function getTopCategory($catid) {

    $CI = & get_instance();
    $CI->db->select('*');
    $CI->db->from('categories');
    $CI->db->where('id', $catid);
    $query = $CI->db->get();
    $result = $query->row();
    //return $catid; // for testing return working
    if($result->parent_id==0){
        //echo $catid -- working result 350
        return $catid; // root parent, not successfully returning the result
    }else{
        return getTopCategory($result->parent_id);  // MODIFIED here
    }

}