PHP:如何合并子数组?

时间:2017-05-22 14:29:58

标签: php arrays loops

我有:

$colors = array(
    'apple' => array('green', 'red'),
    'grape' => array('green', 'purple'),
);

$countries = array(
    'apple' => array('china', 'usa')
    'grape' => array('spain', 'france')
);

预期输出:

$result = array(
    'apple' => array('green', 'red', 'china', 'usa'),
    'grape' => array('green', 'purple', 'spain', 'france'),
);

我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:3)

$result = array_merge_recursive($colors, $countries);

了解详情:http://php.net/manual/en/function.array-merge-recursive.php

答案 1 :(得分:1)

希望这个最简单的一个会有所帮助。

Try this code snippet here

<?php

$colors = array(
    'apple' => array('green', 'red'),
    'grape' => array('green', 'purple'),
);

$countries = array(
    'apple' => array('china', 'usa'),
    'grape' => array('spain', 'france')
);
foreach($colors as $key => &$value)
{
    $value=array_merge($value,$countries[$key]);
}
print_r($colors);