PHP Conference Kansai 2025

array_merge_recursive

(PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8)

array_merge_recursive递归地合并一个或多个数组

说明

array_merge_recursive(array ...$arrays): array

array_merge_recursive() 将一个或多个数组的单元合并起来,一个数组中的值附加在前一个数组的后面。返回作为结果的数组。

如果输入的数组中有相同的字符串键名,则这些值会被合并到一个数组中去,这将递归下去,因此如果一个值本身是一个数组,本函数将按照相应的条目把它合并为另一个数组。需要注意的是,如果数组具有相同的数值键名,后一个值将不会覆盖原来的值,而是附加到后面。

参数

arrays

数组变量列表,进行递归合并。

返回值

一个结果数组,其中的值合并自附加的参数。如果未传递参数调用,则会返回一个空 array

更新日志

版本 说明
7.4.0 允许不传递参数调用,之前的版本中至少需要一个参数。

示例

示例 #1 array_merge_recursive() 例子

<?php
$ar1
= array("color" => array("favorite" => "red"), 5);
$ar2 = array(10, "color" => array("favorite" => "green", "blue"));
$result = array_merge_recursive($ar1, $ar2);
print_r($result);
?>

以上示例会输出:

Array
(
    [color] => Array
        (
            [favorite] => Array
                (
                    [0] => red
                    [1] => green
                )

            [0] => blue
        )

    [0] => 5
    [1] => 10
)

参见

添加备注

用户贡献的备注 1 note

up
175
gabriel dot sobrinho at gmail dot com
15 years ago
I refactored the Daniel's function and I got it:

<?php
/**
* array_merge_recursive does indeed merge arrays, but it converts values with duplicate
* keys to arrays rather than overwriting the value in the first array with the duplicate
* value in the second array, as array_merge does. I.e., with array_merge_recursive,
* this happens (documented behavior):
*
* array_merge_recursive(array('key' => 'org value'), array('key' => 'new value'));
* => array('key' => array('org value', 'new value'));
*
* array_merge_recursive_distinct does not change the datatypes of the values in the arrays.
* Matching keys' values in the second array overwrite those in the first array, as is the
* case with array_merge, i.e.:
*
* array_merge_recursive_distinct(array('key' => 'org value'), array('key' => 'new value'));
* => array('key' => array('new value'));
*
* Parameters are passed by reference, though only for performance reasons. They're not
* altered by this function.
*
* @param array $array1
* @param array $array2
* @return array
* @author Daniel <daniel (at) danielsmedegaardbuus (dot) dk>
* @author Gabriel Sobrinho <gabriel (dot) sobrinho (at) gmail (dot) com>
*/
function array_merge_recursive_distinct ( array &$array1, array &$array2 )
{
$merged = $array1;

foreach (
$array2 as $key => &$value )
{
if (
is_array ( $value ) && isset ( $merged [$key] ) && is_array ( $merged [$key] ) )
{
$merged [$key] = array_merge_recursive_distinct ( $merged [$key], $value );
}
else
{
$merged [$key] = $value;
}
}

return
$merged;
}
?>

This fix the E_NOTICE when the the first array doesn't have the key and the second array have a value which is a array.
To Top