PHP如何将旧数组按store字段去重后推入新数组?附实现代码
现有代码存在的问题
- 索引不匹配错误:遍历原数组用到的
$nkey是原数组$data的键,而新数组$sorted_array通过array_push追加元素,键是从0开始的连续整数,两者索引完全不对应,访问$sorted_array[$nkey]时大概率会触发未定义数组索引报错。 - 去重逻辑错误:仅对比了新数组中和原数组同索引位置的元素的
store字段,没有遍历整个新数组检查当前值是否已存在,完全无法满足全局去重的需求。 - 多余调试代码:代码中保留的
dd()是调试终止函数,执行后会直接中断程序运行,循环根本无法完整执行。
修复后的实现代码
场景1:仅判断store字段是否重复判定为相同对象
$sorted_array = array(); foreach ($data as $value) { $exists = false; // 遍历新数组全量检查store是否已存在 foreach ($sorted_array as $existed_item) { if ($existed_item['store'] == $value['store']) { $exists = true; break; } } if (!$exists) { array_push($sorted_array, $value); } }
场景2:整个数组对象完全相同才判定为重复
可以直接用PHP内置的in_array函数简化逻辑:
$sorted_array = array(); foreach ($data as $value) { if (!in_array($value, $sorted_array)) { array_push($sorted_array, $value); } }
性能优化方案
如果原数组数据量较大,双重循环的O(n²)复杂度效率较低,可以用临时哈希表存储已出现的store值,判断复杂度降到O(1):
$sorted_array = array(); $existed_stores = []; foreach ($data as $value) { $current_store = $value['store']; if (!isset($existed_stores[$current_store])) { $existed_stores[$current_store] = true; array_push($sorted_array, $value); } }
内容的提问来源于stack exchange,提问作者shafnaz
相关产品推荐
相关产品推荐

