亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

按類別格式化 rest Api 組字段

按類別格式化 rest Api 組字段

PHP
交互式愛情 2023-05-12 14:31:50
我是 API 的新手,我使用 Codeigniter 從 MySql 數據庫產品創建一個 API,該產品具有以下字段:Amount、quantity、customerName、CustomerPhone、CustomerAddress 結果看起來:```[    {        "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"},    },```我的意思是用名稱 customer info 將 3 個字段 concernign customers 分組我的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);    }```
查看完整描述

2 回答

?
慕無忌1623718

TA貢獻1744條經驗 獲得超4個贊

你的 Products 格式是基于數據庫的,因此如果你想改變結果格式,你必須手動構建它。您需要在返回數據之前循環結果。


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


查看完整回答
反對 回復 2023-05-12
?
GCT1015

TA貢獻1827條經驗 獲得超4個贊

您不能通過查詢執行此操作,您必須遍歷結果并將其更改為所需的格式,就像這樣 -


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

看看這是否對您有幫助。


查看完整回答
反對 回復 2023-05-12
  • 2 回答
  • 0 關注
  • 151 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號