Franky
Franky

Reputation: 912

add data on a array query result

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 ?

Upvotes: 0

Views: 171

Answers (2)

Meneer Venus
Meneer Venus

Reputation: 1045

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.

Upvotes: 2

Mauro Tamm
Mauro Tamm

Reputation: 360

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.

Upvotes: 1

Related Questions