使用相同的键将值添加到多维数组

时间:2018-01-26 12:39:02

标签: php arrays

如果我有:

<?php
$array1= array (
    "John"  => array("10" , "Holland"),
    "Cindy"  => array("20" , "Sweden"),
);


$array2= array (
    "John"  => ("Amsterdam"),
    "Cindy"  => ("Stockholm"),
);
?>

如何将 $ array1 的值添加到 $ array1 (相同的键)以获取 $ array3

<?php
$array3= array (
    "John"  => array("10" , "Holland", "Amsterdam"),
    "Cindy"  => array("20" , "Sweden", "Stockholm"),
    );
?>

1 个答案:

答案 0 :(得分:5)

您可以使用功能array_merge_recursive()

执行此操作
  $array1= array (
        "John"  => array("10" , "Holland"),
        "Cindy"  => array("20" , "Sweden"),
    );


$array2= array (
    "John"  => ("Amsterdam"),
    "Cindy"  => ("Stockholm"),
);

echo '<pre>'; print_r(array_merge_recursive($array1,$array2));

输出

Array
(
    [John] => Array
        (
            [0] => 10
            [1] => Holland
            [2] => Amsterdam
        )

    [Cindy] => Array
        (
            [0] => 20
            [1] => Sweden
            [2] => Stockholm
        )

)