控制器:
<?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时,它抛出了意外的异常,但是我的预期输出却不同。那么,我该怎么做?请帮助我。
谢谢
答案 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);
}