如何匹配两个数组的共有元素并合并,为city数组新增post_code字段
解决方案
你可以先将邮编数组转换为城市名为键、邮编为值的映射表,再遍历城市数组匹配追加字段,该方案时间复杂度为O(n+m),数据量大时效率远高于嵌套循环。
PHP 实现代码
// 示例数组定义(可替换为你自己的实际数组) $city = [ ['id' => 1, 'city' => 'Budapest', 'population' => 1700000], ['id' => 2, 'city' => 'Szeged', 'population' => 160000] ]; $city_postcode = [ ['name' => 'Budapest', 'post_code' => 12345], ['name' => 'Szeged', 'post_code' => 33356] ]; // 1. 构造邮编映射表 $postcodeMap = []; foreach ($city_postcode as $item) { $postcodeMap[$item['name']] = $item['post_code']; } // 2. 遍历城市数组追加字段 foreach ($city as &$item) { if (isset($postcodeMap[$item['city']])) { $item['post_code'] = $postcodeMap[$item['city']]; } // 未匹配到需要默认值可改为:$item['post_code'] = $postcodeMap[$item['city']] ?? '默认邮编'; } unset($item); // 解除引用避免后续逻辑异常 // 打印验证结果 print_r($city);
JavaScript 实现代码
如果是JS场景可以用以下实现:
// 示例数组定义 const city = [ {id: 1, city: 'Budapest', population: 1700000}, {id: 2, city: 'Szeged', population: 160000} ]; const cityPostcode = [ {name: 'Budapest', post_code: 12345}, {name: 'Szeged', post_code: 33356} ]; // 构造映射表 const postcodeMap = Object.fromEntries(cityPostcode.map(item => [item.name, item.post_code])); // 追加字段 const result = city.map(item => ({ ...item, post_code: postcodeMap[item.city] // 未匹配到需要默认值可改为:post_code: postcodeMap[item.city] || '默认邮编' })); // 打印验证 console.log(result);
内容的提问来源于stack exchange,提问作者Norbert Eper
相关产品推荐
相关产品推荐

