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

PHP数组按ISO分组并合并同日期金额问题求助

问题:按国家ISO分组并累加同日期金额

我通过以下代码生成了包含国家信息的数组:

$newCountry = array(
    'reservation_id' => $countryId,
    'amount' => $countryAmount,
    'iso' => $countryIso,
    'start' => $event['start']
);

if(!$countryId == null){
    array_push($eventsCountries, $newCountry);
}

需求是将数组按[CountryIso] => ([0] => ItemArray)的结构分组,且同一ISO分组内如果有相同start日期,要将对应amount累加。

目前编写的代码如下:

$t2 = [];foreach ($eventsCountries as $item) {   
    if (!isset($t2[$item['iso']])) {
            $t2[$item['iso']] = array();
     }
    
    $newdata =  array (
      'amount' => $item['amount'],
      'start' => $item['start']
    );
    array_push($t2[$item['iso']], $newdata);
}

输出结果:

Array ( [DK] => Array ( [0] => Array ( [amount] => 2 [start] => 2023-03-07 00:00:00 ) [1] => Array ( [amount] => 25 [start] => 2023-03-03 00:00:00 ) ) [AF] => Array ( [0] => Array ( [amount] => 5 [start] => 2023-03-03 00:00:00 ) [1] => Array ( [amount] => 5 [start] => 2023-03-03 00:00:00 ) ) )

这段代码仅实现了按ISO分组,未完成同日期金额累加的功能,求解决方法。


解决方案

修改代码逻辑,利用start日期作为ISO分组内的临时键,判断是否已存在该日期的记录,存在则累加金额,不存在则初始化,最后再将每个ISO下的关联数组转为索引数组,满足你要的结构:

$t2 = [];
foreach ($eventsCountries as $item) {
    $iso = $item['iso'];
    $start = $item['start'];
    $amount = $item['amount'];
    
    // 初始化ISO分组
    if (!isset($t2[$iso])) {
        $t2[$iso] = [];
    }
    
    // 检查当前ISO下是否已有该start日期的记录
    if (isset($t2[$iso][$start])) {
        // 存在则累加金额
        $t2[$iso][$start]['amount'] += $amount;
    } else {
        // 不存在则新增记录
        $t2[$iso][$start] = [
            'amount' => $amount,
            'start' => $start
        ];
    }
}

// 将每个ISO下的关联数组转为索引数组
foreach ($t2 as $iso => $items) {
    $t2[$iso] = array_values($items);
}

代码说明

  1. 遍历原数组时,先用iso和start作为层级判断的依据,避免重复创建相同日期的条目
  2. 若同一ISO下已存在相同start的记录,直接累加amount
  3. 最后通过array_values()将每个ISO分组内的关联数组转为索引数组,符合你需要的[0] => ItemArray结构

运行后,你的示例数据会输出:

Array ( [DK] => Array ( [0] => Array ( [amount] => 2 [start] => 2023-03-07 00:00:00 ) [1] => Array ( [amount] => 25 [start] => 2023-03-03 00:00:00 ) ) [AF] => Array ( [0] => Array ( [amount] => 10 [start] => 2023-03-03 00:00:00 ) ) )

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 20:55:17