Reputation: 1752
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);
Upvotes: 0
Views: 416
Reputation: 2034
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
}
}
Upvotes: 1
Reputation: 16502
You have to return the recursive function inside of your else
block:
// ...
} else {
return getTopCategory($result->parent_id);
}
Upvotes: 1
Reputation: 4098
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.
Upvotes: 1