0

I have the function below in my model which return an array of data. I want to make another operation on each row and add the result to array of data before to return it.

 function get_all_annonce()
    {
        $this->db->select(" * from annonce");
        $this->db->order_by("annonce.DATEDEBUTANNONCE","asc");
        $q=$this->db->get();
        if($q->num_rows()>0)
        {
            foreach($q->result() as $row)
            {

                $data[]=$row;
                //I try to add another result
                $experience=$this->get_experience($row->NUMUSER); 
                $data['experience']=$experience;
            }
            return $data;
        }
    }

But I have an error when I try to access to $experience or $row->'experience' in my view. How can I fix it ?

0

2 Answers 2

2

The $data variable is defined in the wrong scope. You defined it inside the foreach loop but you try to return it after. Try adding $data = Array(); above the foreach.

Sign up to request clarification or add additional context in comments.

Comments

1

In addition to the answer above. First you have unnecessary assignments, you can do it in one line. 2nd - when you use [] - it will create index automatically and the row will be added as an array to that index. You get a multidimensional array( 0 => result 1, 1 => result 2 etc).

If you want to add the 'experience' key to the result, you cannot add it directly to data.

You get an array that will have keys 0,1,2,3,4 ... 'experience' as last key - each time it is overwritten.

One way would be to use a variable for key (or use for loop instead):

        $i = 0;
        foreach($q->result() as $row)
        {
            $data[$i]=$row;
            $data[$i]['experience'] = $this->get_experience($row->NUMUSER); 
        }

If you used only [] for both, it would assign different key for each one every iteration.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.