数组合并/插入异常:如何移除合并后的数字索引键?
解决数组合并时的数字索引问题
你的问题出在使用array_push往关联数组(workingHours的每个元素都是关联数组)中添加元素——PHP会自动为这些新增元素分配数字索引(也就是你看到的0、1),这就导致了不符合预期的结构。
正确的解决方案
我们可以先把折扣数据按dayName分组,再批量合并到对应营业时间条目中,既避免数字索引,又提升效率:
步骤1:按日期分组折扣数据
先把discount数组按dayName整理成分组结构,方便后续快速查找:
// 按dayName分组折扣数据 $discountsGrouped = []; foreach ($returnDataAns['discount'] as $discountItem) { $day = $discountItem['dayName']; if (!isset($discountsGrouped[$day])) { $discountsGrouped[$day] = []; } $discountsGrouped[$day][] = $discountItem; }
步骤2:合并到营业时间数组
遍历workingHours,给对应日期的条目添加一个discounts字段,存放该天的所有折扣:
// 遍历营业时间数组,合并对应折扣 foreach ($returnDataAns['workingHours'] as &$hourItem) { $day = $hourItem['dayName']; if (isset($discountsGrouped[$day])) { // 添加discounts字段,值为该天的折扣数组 $hourItem['discounts'] = $discountsGrouped[$day]; } } // 释放引用,避免后续代码意外修改数组 unset($hourItem);
最终效果
这样处理后,你会得到结构清晰且无数字索引的结果,示例如下:
"workingHours": [ { "opening": "", "closing": "", "dayName": "monday", "discounts": [ { "from_time": "06:13:16", "to_time": "04:14:11", "discount": "20", "dayName": "monday" }, { "from_time": "06:59:16", "to_time": "04:19:11", "discount": "20", "dayName": "monday" } ] }, // 其他日期的条目... ]
为什么原来的代码会出现数字索引?
array_push的作用是给索引数组追加元素,而workingHours的每个元素是关联数组(键为字符串)。当你强行用array_push往关联数组里加元素时,PHP会自动为这些元素分配数字键,这就是0、1出现的原因。
内容的提问来源于stack exchange,提问作者Jim Kasprowicz
相关产品推荐
相关产品推荐

