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

PHP中如何通过foreach循环将所有商品项存入请求数组?

问题分析

你的代码存在两个核心问题:

  • 未对$jcart->get_contents()的商品列表做遍历处理,直接引用循环结束后的$item变量,自然只会保留最后一个商品的数据。
  • $req的数组结构错误,你把action等配置字段放在了一个索引数组元素中,后续的items键会变成数组的第二个独立元素,导致整体结构不符合预期。
修正代码

正确的做法是先初始化$req的基础配置,再通过循环将所有商品追加到$req['items']数组中:

// 初始化请求的基础配置
$req = array(
    'action' => 'SALE',
    'type' => 1,
    'countryCode' => 826,
    'currencyCode' => 826,
    'items' => array() // 先初始化items为空数组
);

// 遍历所有商品,逐个添加到items数组
foreach ($jcart->get_contents() as $item) {  
    $req['items'][] = array(
        'description' => urlencode($item['name']),
        'amount' => urlencode($item['price']),
        'quantity' => urlencode($item['qty'])
    );
}
验证结果

修正后$req的items字段会包含所有商品数据,结构示例如下:

array(
    'action' => 'SALE',
    'type' => 1,
    'countryCode' => 826,
    'currencyCode' => 826,
    'items' => array(
        array('description' => 'Product1', 'amount' => '519', 'quantity' => '1'),
        array('description' => 'Product2', 'amount' => '339', 'quantity' => '1')
    )
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 07:15:37