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

如何让Laravel API响应不含索引并符合指定格式?

Laravel API 响应格式调整问题

问题描述

开发的Laravel API接收如下JSON请求数据:

{"productlist": [{"student_id": 216, "product_id": 4, "product_qty": 2},{"student_id": 216, "product_id": 6, "product_qty": 2}]}

当前服务端处理代码:

$data = $request->json()->all();
$productlist = $data['productlist'];
$total_amount = 0;
foreach($productlist as &$pl){
    $pl['total_amount'] = $this->get_itemdetail($pl['product_id'])[0]->item_price * $pl['product_qty'];
    $pl['product_detail'] = $this->get_itemdetail($pl['product_id']);
    $total_amount+= $this->get_itemdetail($pl['product_id'])[0]->item_price * $pl['product_qty'];
}
$productlist['cart_total'] = $total_amount;
return response()->json(['data'=>$productlist, 'status'=> 200, 'message'=> 'Cart Processing Successfully']);

当前API响应会包含数字索引,不符合需求,期望响应不含数字索引且包含cart_total字段(已修正原期望中的JSON语法错误,合法JSON对象不允许存在无键子对象):

{
    "data": {
        "items": [
            {
                "student_id": 216,
                "product_id": 4,
                "product_qty": 2,
                "total_amount": 100,
                "product_detail": [
                    {"id": 4, "item_name": "Chocolate", "description": "dairy milk chocolate", "item_price": "50", "total_stock": 160}
                ]
            },
            {
                "student_id": 216,
                "product_id": 6,
                "product_qty": 2,
                "total_amount": 46,
                "product_detail": [
                    {"id": 6, "item_name": "Biscuit", "description": "Biscuit", "item_price": "23", "total_stock": 10}
                ]
            }
        ],
        "cart_total": 146
    },
    "status": 200,
    "message": "Cart Processing Successfully"
}

解决方案

1. 优化数据结构与重复查询

原代码中$productlist是索引数组,直接添加cart_total会导致数组混合索引与关联键,JSON序列化后保留数字索引;同时重复调用get_itemdetail三次会降低性能,需优化复用查询结果。

修改后的代码如下:

$data = $request->json()->all();
$productlist = $data['productlist'];
$total_amount = 0;
$processedItems = [];

foreach($productlist as $pl){
    // 仅调用一次商品详情接口,复用结果
    $itemDetail = $this->get_itemdetail($pl['product_id']);
    $itemPrice = $itemDetail[0]->item_price;
    $itemTotal = $itemPrice * $pl['product_qty'];
    
    $processedItems[] = [
        'student_id' => $pl['student_id'],
        'product_id' => $pl['product_id'],
        'product_qty' => $pl['product_qty'],
        'total_amount' => $itemTotal,
        'product_detail' => $itemDetail
    ];
    
    $total_amount += $itemTotal;
}

// 构造包含商品列表与总价的关联数组
$responseData = [
    'items' => $processedItems,
    'cart_total' => $total_amount
];

return response()->json([
    'data' => $responseData,
    'status' => 200,
    'message' => 'Cart Processing Successfully'
]);

2. 代码说明

  • 将处理后的商品列表存入processedItems数组,再放入responseData的items键下,与cart_total同级,确保data是纯关联数组(JSON对象),无数字索引。
  • 复用get_itemdetail的查询结果,减少数据库/接口调用次数,提升性能。
  • 采用items数组存放商品列表,符合JSON语法规范,同时满足“无数字索引、包含总价”的需求。

内容的提问来源于stack exchange,提问作者Hamza Zafeer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 07:23:23