简体   繁体   中英

codeigniter, how to select table data and display result in json format?

I have to fetch data from database table and display result in json format.

my table dr_hospital looks like:

在此输入图像描述

I have to fetch data group by city_id and its result should display in the jason format.

My result json must look like :

[
  {"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"

  }]}

]

For getting above json format what all changes should I have do in my code? my code looks like:

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); 
        }
}

Thanking in advance.

    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));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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