按类别格式化 rest Api 组字段

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

    }```


交互式爱情
浏览 122回答 2
2回答

慕无忌1623718

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

GCT1015

您不能通过查询执行此操作,您必须遍历结果并将其更改为所需的格式,就像这样 -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看看这是否对您有帮助。
打开App,查看更多内容
随时随地看视频慕课网APP