Welcome Guest, Not a member yet? Register   Sign In
recursive function in model is not returning values as it echo all values within function
#1

[eluser]Unknown[/eluser]
Hi All,

i have write the function in a model which call it self as recursive call end to a basic condition it echo all values but didn't return value to me in controller.

please help. below i m writing code of my function please check and ask if there is any issue with this.



Code:
function get_upper_most_parent($page_id)
{
    $this->db->select('page_id,page_parent');
    $this->db->from('pages');
    $this->db->where('page_id',$page_id);
    $result=$this->db->get();
            
    $row=$result->row();
                
    $parent_id=$row->page_parent;
    if($parent_id==0)
    {
        return $page=$row->page_id;
    }
    else
    {
        $this->get_upper_most_parent($parent_id,1);
    }
}

Thanks in Advance


Regards
#2

[eluser]mddd[/eluser]
The problem is, that you don't do anything with the result of your recursive function. The function will call itself until it reaches 'parent_id=0'. The last recursion of the function will then return the correct id. But this 'return value' goes to the previous recursion. And that recursion doesn't do anything with the value!

I think the solution is simple:
Code:
// replace this:
$this->get_upper_most_parent($parent_id,1);
// with this:
return $this->get_upper_most_parent($parent_id);

That way, every recursion returns its result to the one before. And eventually: back to the main call you make to the model.

(Note: you are making a lot of calls to the database this way. I think there are quicker methods to get the main parent. For instance: if you know te maximum depth of your pages, you could join multiple times on the same table and check the correct parent in php. You'll need only 1 call to the database and fetch 1 row to do it).
#3

[eluser]Unknown[/eluser]
Thanks




Theme © iAndrew 2016 - Forum software by © MyBB