如何合并单个数组中日期时间相同的元素,array_merge_recursive不生效怎么处理
解决方案
核心思路
用date、from_time、to_time三个字段拼接生成唯一的分组键,遍历过程中直接按键聚合id,逻辑简单性能也更高,不需要依赖array_merge_recursive处理。
代码实现
方案1:直接修改原有构建逻辑(推荐)
在生成$options的阶段直接完成合并,不需要二次处理数组:
$options = []; foreach ($arrays as $array) { $current_id = last(str_split($array['id'])); $current_date = substr($array['id'],0,-2); $current_from = Carbon::createFromTimestamp($array['pickup']['from'])->format('H'); $current_to = Carbon::createFromTimestamp($array['pickup']['to'])->format('H'); // 拼接唯一分组标识,分隔符用不会出现在字段值里的字符即可 $group_key = $current_date . '|' . $current_from . '|' . $current_to; // 该时间段首次出现时初始化条目 if (!isset($options[$group_key])) { $options[$group_key] = [ 'date' => $current_date, 'from_time' => $current_from, 'to_time' => $current_to, 'id' => [] ]; } // 把当前id存入对应分组的id数组 $options[$group_key]['id'][] = $current_id; } // 可选:如果需要重置数组为0开始的数字索引,调用array_values $options = array_values($options);
方案2:对已生成的$options做二次处理
如果不想修改原有生成$options的代码,可以单独加这段逻辑处理:
$grouped_result = []; foreach ($options as $item) { $group_key = $item['date'] . '|' . $item['from_time'] . '|' . $item['to_time']; if (!isset($grouped_result[$group_key])) { $grouped_result[$group_key] = $item; // 将初始的字符串id转为数组格式 $grouped_result[$group_key]['id'] = (array)$item['id']; continue; } // 已有分组则追加id $grouped_result[$group_key]['id'][] = $item['id']; } // 重置索引得到最终结果 $options = array_values($grouped_result);
两种方案运行后得到的数组都完全符合你要求的输出格式,相同时间段的所有id会被合并到同一个id数组字段中。
内容的提问来源于stack exchange,提问作者Farshad
相关产品推荐
相关产品推荐

