Abin Jacob Abin Jacob - 3 months ago 11
JSON Question

Codeigniter, How to get database table data displayed in json format?

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.

Answer

Retrieve the record in array and then encode it

$result = $this->db->get('country')->result_array();
print_r(json_encode($result));