在树形结构中找到顶级类别,我正在使用此
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);
}
}
如果我在getTopCategory($ catid)中使用echo它正确地给出了父类别id,但它没有将日期返回到getTopCategory($ category_id);
答案 0 :(得分:1)
然后返回,请在代码中查看我的评论:
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);
}
}
当你进行递归调用时,你需要从递归调用本身返回值,这样它就可以一直回到echo命令。
答案 1 :(得分:1)
您必须在else
块内返回递归函数:
// ...
} else {
return getTopCategory($result->parent_id);
}
答案 2 :(得分:1)
你也应该在else中返回,因为如果条件转到else,那么它会调用自身并具有返回值,但不会在第一时间返回它。
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
}
}