首页 > 解决方案 > 如果两个数组中都存在一项,如何合并两个数组?

问题描述

我想用邮政编码值扩展我的城市数组。如果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
        )
)

标签: phphtmlsqlarrays

解决方案


作为替代方案,您可以在 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);

推荐阅读