codeigniter,如何选择表数据并以json格式显示结果?

时间:2016-09-03 09:40:30

标签: php mysql json codeigniter

我必须从数据库表中获取数据并以json格式显示结果。

我的表 dr_hospital 看起来像:

enter image description here

我必须通过 city_id 获取数据组,其结果应以jason格式显示。

我的结果json必须如下:

[
  {"city_id": "13","hospitals":[
   {
    "id": "1",
    "name": "Medical Trust Hospital",
    "address": "MG Road, Cochin - 682 016, Kerala, India."

  },
  {
    "id": "2",
    "name": "PVS Memorial Hospital",
    "address": "Kaloor, Cochin- 682017, Kerala, India."
  }]},
 {"city_id": "1","hospitals":[  
{
    "id": "3",
    "name": "Blacktown Hospital",
    "address": "Sydney"

  },
  {
    "id": "4",
    "name": "Fairfield Hospital",
    "address": "Sydney"
  }]},
 {"city_id": "2","hospitals":[ 
  {
    "id": "5",
    "name": "Angliss Hospital",
    "address": "31 Albert Road Melbourne"

  },
  {
    "id": "6",
    "name": "Avenue Plastic Surgery",
    "address": "20 The Avenue Windsor"

  }]}

]

为了获得json格式,我应该在代码中做什么更改? 我的代码看起来像:

public function hospitalAction()
{
      $this->db->select('*');
      $result = $this->db->get('dr_hospital')->result_array();

        if($result)
        {
           print_r(json_encode($result));    
        }
        else
        {
             $detail[] = array(
            'status'=>'unsuccess', 
            'message'=>'no hospital available',

           );

          echo  json_encode($detail); 
        }
}

提前感谢。

1 个答案:

答案 0 :(得分:0)

    public function hospitalAction()
{
    $result1 = $this->db->query("SELECT city_id from dr_hospital group by city_id");
    $result1=$result1->result();
    $arr= array();
    foreach ($result1 as $res) {
        $result = $this->db->query("SELECT * from dr_hospital where city_id='".$res->city_id."'");
        $result=$result->result();
        $arr[$res->city_id]=$result;
    }
    var_dump(json_encode($arr));
}