Restful API 在 codeigniter 中抛出意外输出

Restful API throw unexpected output in codeigniter

控制器:

<?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 时,它会抛出意外,但我的预期输出是不同的。那么,我该怎么做呢?请帮助我。

谢谢

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

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