我是API新手,我使用Codeigniter从MySql Databse产品创建APi,这些产品具有 字段 : 金额 , 数量, 客户姓名, 客户电话, 客户地址 罗尔特看起来:
```[
{
"Id": "1",
"Amount": "21542",
"quantity": "52",
"customerName": "John",
"CustomerPhone": "254215",
"CustomerAddress": "road tvz120",
},```
但我希望它看起来像这样:
```[
{
"Id": "1",
"Amount": "21542",
"quantity": "52",
"customerInfo":{
"customerName": "John",
"CustomerPhone": "254215",
"CustomerAddress": "rue tvz120"},
},```
我的意思是将 3 个字段与客户信息分组,名称为客户信息
我的PHP代码是
```public function index_get($id = 0)
{
if(!empty($id)){
$data = $this->db->get_where("Products", ['Id' => $id])->row_array();
}else{
$data = $this->db->get("Products")->result();
}
$this->response($data, REST_Controller::HTTP_OK);
}```
您的产品格式基于数据库,因此如果要更改结果格式,则必须手动构造它。您需要在返回数据之前循环结果。
if(!empty($id)){
$data = $this->db->get_where("Products", ['Id' => $id])->row_array();
}else{
$data = $this->db->get("Products")->result();
$newdata = array();
foreach($data as $row)
{
$newdata[] = array(
"Id" => $row->id,
"Amount" => $row->amount,
"quantity" => $row->quantity,
"customerInfo" => array(
"customerName" => $row->customerName,
"CustomerPhone" => $row->CustomerPhone,
"CustomerAddress" => $row->CustomerAddress,
)
);
}
$data = $newdata;
}
$this->response($data, REST_Controller::HTTP_OK);
您无法通过查询执行此操作,您必须遍历结果并将其更改为所需的格式,如下所示 -
if(!empty($id)){
$result = $this->db->get_where("Products", ['Id' => $id])->result();
// I'll advise to use result() here instead of row_array() so that you don't face any issue when there's only one row.
}else{
$result = $this->db->get("Products")->result();
}
foreach($result as $res){
$new_result[] = array(
"Id" => $res->Id,
"Amount" => $res->Amount,
"quantity" => $res->quantity,
"customerInfo" => array(
"customerName" => $res->customerName,
"CustomerPhone" => $res->CustomerPhone,
"CustomerAddress" => $res->CustomerAddress
)
);
}
$this->response($new_result, REST_Controller::HTTP_OK); // send newly created array instead
看看这是否对您有帮助。