简体   繁体   English

Codeigniter,如何获取以json格式显示的数据库表数据?

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

I have to display the result in json format. 我必须以json格式显示结果。 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 (,) . 我必须在[]中得到这个json并用逗号(,)分隔。 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. 我应该在代码中完成所有更改。

Retrieve the record in array and then encode it 检索数组中的记录,然后对其进行编码

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

在模型写

return $query->result_array();

Use result_array() . 使用result_array()

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM