php - 如果两个数组中都存在一项,如何合并两个数组?
问题描述
我想用邮政编码值扩展我的城市数组。如果city_postcode数组包含城市数组名称记录,则将邮政编码值推入城市数组。这就是我想以某种方式实现的目标。
城市数组:
Array
(
[0] => Array
(
[id] => 1
[city] => Budapest
[population] => 1700000
)
[1] => Array
(
[id] => 2
[city] => Szeged
[population] => 160000
)
)
city_postcode 数组:
Array
(
[0] => Array
(
[name] => Budapest
[post_code] => 12345
)
[1] => Array
(
[name] => Szeged
[post_code] => 33356
)
)
我想要的结果:
Array
(
[0] => Array
(
[id] => 1
[city] => Budapest
[population] => 1700000
[post_code] => 12345
)
[1] => Array
(
[id] => 2
[city] => Szeged
[population] => 160000
[post_code] => 33356
)
)
解决方案
作为替代方案,您可以在 foreach 循环中使用“参考”PHP,如下所示
$city = array(
0 => array(
'id' => 1,
'city' => "Budapest",
'population' => 1700000
),
1 => array(
'id' => 2,
'city' => "Szeged",
'population' => 160000
)
);
$city_postcode = array(
0 =>array(
'name' => 'Budapest',
'post_code' => 12345
),
1 => array(
'name' => 'Szeged',
'post_code' => 33356
)
);
foreach ($city as $ckey => &$cval) {
$cval['post_code'] = $city_postcode[$ckey]['post_code'];
}
unset($cval);
var_dump($city);
推荐阅读
- r - 如何将向量中的所有项乘以一个值?
- sql - 前缀为“%”的 LIKE 运算符中的索引丢失
- javascript - 功能是如何知道完成的以及哪些汽车放在第一位和第二位?
- excel - 如何根据另一个值突出显示单元格,填充单元格后删除突出显示
- javascript - 创建出现在没有空格的字符串中的单词列表 - 说明单词出现多次的情况
- python - 如何检测唤醒词或是否说出任何词
- mysql - 为什么这个查询不起作用而这个查询起作用?
- material-ui - MenuItem 中的 TextField - onKeyDown 事件干扰 TextField 中的 onChange
- flutter - Flutter/Dart http get 请求响应不完整
- azure - 我们在数据流 Azure 中是否有合并功能