Restful API在Codeigniter中引发意外输出

时间:2019-06-04 06:16:17

标签: php json rest codeigniter-3 api-design

控制器:

<?php
    require APPPATH . '/libraries/REST_Controller.php';
    use Restserver\Libraries\REST_Controller;
    class User extends REST_Controller 
    {
        function __construct() 
        {
            parent::__construct();
            $this->load->database();
        }
        function country_state_get()
        {
            $this->db->select('id,name');
            $this->db->from('countries');
            $sql = $this->db->get();
            $data = $sql->result_array();
            foreach($data as $row)
            {
                $this->db->select('id,name');
                $this->db->from('states');
                $this->db->where('country_id',$row['id']);
                $sqls = $this->db->get();
                $data2 = $sqls->result_array();
            }
            $result= [
                "Country" => $data,
                "state" => $data2
            ];
            $this->response($result, 200);
        }
    }

意外的输出:

{
"Country": [
    {
        "id": "1",
        "name": "Afghanistan"
    },
    {
        "id": "2",
        "name": "Albania"
    },
    {
        "id": "3",
        "name": "Algeria"
    }
]

}

预期输出:

{
"Country": [
    {
        "id": "1",
        "name": "Afghanistan",
        "state": ["Badakhshan", "Badghis", "Baghlan"]
    },
    {
        "id": "2",
        "name": "Albania",
        "state": ["Berat", "Dibres", "Durres"]
    },
    {
        "id": "3",
        "name": "Algeria",
        "state": ["Adrar", "Ain Defla", "Ain Temouchent"]
    }
]

}

我必须使用codeigniter框架创建简单的国家和州api。如上所述,在这里我得到了意外的输出。当我在本地主机服务器上访问URL时,它抛出了意外的异常,但是我的预期输出却不同。那么,我该怎么做?请帮助我。

谢谢

1 个答案:

答案 0 :(得分:0)

使用下面的country_state_get代码更新您的function函数

    function country_state_get()
     {
          $this->db->select('id,name');
          $this->db->from('countries');
          $sql = $this->db->get();
          $data = $sql->result_array();
          foreach($data as $key => $row)
          {
             $this->db->select('id,name');
             $this->db->from('states');
             $this->db->where('country_id',$row['id']);
             $sqls = $this->db->get();
             $data2 = $sqls->result_array();
             $data[$key]['state'] =  $data2;
          }

        $result= [ "Country" => $data ];
        $this->response($result, 200);
}