You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在CodeIgniter中分组REST API返回的客户字段为customerInfo

如何在CodeIgniter REST API中将客户字段分组到customerInfo对象中?

嘿,刚接触API开发就能写出基础的REST接口已经很棒了!你想要把三个客户相关字段打包到customerInfo对象里的需求很合理,我来帮你修改代码实现这个结构。

修改后的完整代码

public function index_get($id = 0) {
    if(!empty($id)){
        // 获取单条产品数据
        $data = $this->db->get_where("Products", ['Id' => $id])->row_array();
        
        // 只有当数据存在时才处理字段分组
        if ($data) {
            // 把客户字段打包到customerInfo对象中
            $data['customerInfo'] = [
                'customerName' => $data['customerName'],
                'CustomerPhone' => $data['CustomerPhone'],
                'CustomerAddress' => $data['CustomerAddress']
            ];
            // 移除原来的平级客户字段
            unset($data['customerName'], $data['CustomerPhone'], $data['CustomerAddress']);
        }
    } else {
        // 获取全部产品数据,用result_array()方便处理关联数组
        $data = $this->db->get("Products")->result_array();
        
        // 遍历每条数据,逐个处理字段分组
        foreach ($data as &$item) {
            $item['customerInfo'] = [
                'customerName' => $item['customerName'],
                'CustomerPhone' => $item['CustomerPhone'],
                'CustomerAddress' => $item['CustomerAddress']
            ];
            unset($item['customerName'], $item['CustomerPhone'], $item['CustomerAddress']);
        }
        unset($item); // 销毁引用,防止后续代码意外修改数组
    }
    
    $this->response($data, REST_Controller::HTTP_OK);
}

关键修改细节说明

  1. 单条数据处理:用row_array()拿到关联数组后,先判断数据是否存在,然后新建customerInfo键,把三个客户字段的值转移进去,最后用unset()删除原来的平级字段,避免重复返回。
  2. 多条数据处理:把result()换成result_array(),这样得到的是关联数组的集合,方便直接修改;用&$item引用遍历,直接修改原数组中的每一项,完成字段分组后同样移除旧字段。
  3. 空数据防护:增加了if ($data)的判断,避免当查询不到数据时执行字段处理逻辑导致报错。

修改后返回的JSON结构就和你期望的完全一致了:

[
    {
        "Id": "1",
        "Amount": "21542",
        "quantity": "52",
        "customerInfo": {
            "customerName": "John",
            "CustomerPhone": "254215",
            "CustomerAddress": "road tvz120"
        }
    }
]

内容的提问来源于stack exchange,提问作者Yahia Baiba

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 22:52:39