3

I have to display the result in json format. my code looks like:

 $this->db->select("*");
        $this->db->from('country');  
        $query = $this->db->get();

        foreach($query->result() as $row)
        {
            echo json_encode($row);
        } 

and the result looks like:

{"id":"1","country_name":"Australia","country_code":"61"}{"id":"2","country_name":"Bangladesh","country_code":"880"}{"id":"3","country_name":"Brazil","country_code":"55"}

I have to get this json in [] and separated by comma (,) . that is I want the result looks like:

[{"id":"1","country_name":"Australia","country_code":"61"},{"id":"2","country_name":"Bangladesh","country_code":"880"},{"id":"3","country_name":"Brazil","country_code":"55"}] 

what all changes should I done in the code.

2
  • Get all rows in an array and encode the result. Commented Aug 26, 2016 at 10:42
  • foreach($query->result() as $row) { $data['id']=$row->id; $data['country_name']=$row->country_name; echo json_encode($data); } not working but the result looks same Commented Aug 26, 2016 at 10:48

3 Answers 3

4

Retrieve the record in array and then encode it

$result = $this->db->get('country')->result_array();
print_r(json_encode($result));
Sign up to request clarification or add additional context in comments.

Comments

2

In model write

return $query->result_array();

Comments

1

Use result_array().

$this->db->select("*");
$this->db->from('country');  
$query = $this->db->get();

foreach($query->result_array() as $row)
{
   echo json_encode($row);
}

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.