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

PHP数组更新:保留结构用其他数组值替换指定字段

问题分析与解决方案

你的代码问题出在第二个foreach循环中:你直接将$sell[$id]重新赋值为只包含month3的新数组,这会完全覆盖掉第一个循环中生成的包含month1、month2的子数组,最终导致每个子数组只剩month3字段,不符合保留原结构的需求。

修正后的代码

foreach ($tempsell1 as $id => $pen) { 
    $sell[$id] = [
        'month1' => $pen->month1,
        'month2' => $pen->month2,
        'month3' => '',
    ];
}
// 只更新子数组中的month3字段,而非替换整个子数组
foreach ($tempsell2 as $id => $pen) { 
    $sell[$id]['month3'] = $pen->month3;
}
dd($sell);

说明

  • 第一个循环正常生成包含month1、month2和初始month3的数组结构
  • 第二个循环通过$sell[$id]['month3']的方式,直接修改对应子数组里的month3值,保留原数组的其他字段和整体结构
  • 运行后即可得到你预期的数组结构:每个子数组保留month1、month2,同时month3被替换为新值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 11:03:25