PHP多维数组匹配:将匹配值合并至目标数组的实现
解决方案
首先我们可以通过构建映射数组的方式高效完成字段匹配与合并,避免嵌套循环的性能损耗,具体实现如下:
假设数组结构(若你的实际结构不同,只需调整对应键名)
// 示例 $array1_1 $array1_1 = [ [ 'stoppage_points' => '站点A', 'name' => '线路1' ], [ 'stoppage_points' => '站点B', 'name' => '线路2' ] ]; // 示例 $getcount $getcount = [ [ 'pickup_trip_location' => '站点A', 'trip_route_id' => 1001, 'c' => 8, 'unused_field' => '无关值' ], [ 'pickup_trip_location' => '站点B', 'trip_route_id' => 1002, 'c' => 5 ] ];
实现代码
// 第一步:把$getcount转成以pickup_trip_location为键的映射数组,只保留需要的字段 $countMap = []; foreach ($getcount as $item) { if (isset($item['pickup_trip_location'])) { $key = $item['pickup_trip_location']; $countMap[$key] = [ 'trip_route_id' => $item['trip_route_id'] ?? null, 'c' => $item['c'] ?? null ]; } } // 第二步:遍历$array1_1,匹配后合并字段 $result = []; foreach ($array1_1 as $item) { $current = $item; $matchKey = $item['stoppage_points'] ?? ''; // 若找到匹配项,合并目标字段 if (isset($countMap[$matchKey])) { $current = array_merge($current, $countMap[$matchKey]); } $result[] = $current; } // 查看最终结果 print_r($result);
代码说明
- 映射数组优化:将
$getcount转换为关联数组后,后续匹配只需通过键直接查找,时间复杂度从嵌套循环的O(n*m)降到O(n+m),数据量越大优势越明显。 - 容错处理:用
??运算符处理字段缺失的情况,避免因数组键不存在导致的报错。 - 灵活调整:如果你的匹配规则不是
pickup_trip_location对应stoppage_points,只需修改映射数组的键名和匹配时的键名即可。
内容的提问来源于stack exchange,提问作者Shiv Kumar
相关产品推荐
相关产品推荐

