李涛自留地
回到顶部
首页 > php学习 > PHP array_merge_recursive() 和 array_replace() 详解:数组合并与替换

PHP array_merge_recursive() 和 array_replace() 详解:数组合并与替换

文章目录

前言

合并数组时 array_merge() 是首选,但遇到关联数组时会有覆盖行为,多维数组时又会有键名重复问题。array_merge_recursive() 和 array_replace() 提供了不同的合并策略。

array_merge_recursive() 递归合并

array_merge_recursive(array1, array2) - 和 array_merge() 类似,但相同字符串键名会将值合并为数组。

<?php
$a = ['colors' => ['red', 'blue'], 'size' => 'M'];
$b = ['colors' => ['green', 'yellow'], 'price' => '100'];
$result = array_merge_recursive($a, $b);
print_r($result);
/*
Array
(
    [colors] => Array ( [0] => red [1] => blue [2] => green [3] => yellow )
    [size] => M
    [price] => 100
)
*/
?>

array_replace() 替换

array_replace(array1, array2, ...) - 用后面数组的值替换前面数组的相同键名值。

<?php
$default = ['name' => '默认', 'email' => 'default@example.com', 'age' => 0];
$user = ['name' => '张三', 'email' => 'zhangsan@example.com'];
$result = array_replace($default, $user);
print_r($result);
// name=张三, email=zhangsan@example.com, age=0 (保留未替换的默认值)
?>

对比

函数 相同键名 适用场景
array_merge() 后面覆盖前面 简单合并
array_merge_recursive() 值合并为数组 配置合并
array_replace() 后面替换前面 默认值覆盖

实战场景

场景1:配置合并

<?php
$defaults = ['database' => ['host' => 'localhost', 'port' => 3306], 'cache' => ['enabled' => true]];
$userConfig = ['database' => ['host' => 'db.example.com']];
$config = array_merge_recursive($defaults, $userConfig);
?>

场景2:默认值覆盖

<?php
function getSettings($userSettings) {
    $defaults = ['theme' => 'light', 'lang' => 'zh', 'notify' => true];
    return array_replace($defaults, $userSettings);
}
?>

踩坑提醒

  1. array_merge_recursive() 会递归合并,可能导致意外的深层数组
  2. array_replace() 不存在的键不会被添加
  3. array_merge_recursive() 相同键名会创建嵌套数组,注意后续处理

总结

  1. array_merge_recursive() 用于配置合并,相同键值合并为数组
  2. array_replace() 用于默认值覆盖,保持默认值结构
  3. 简单合并用 array_merge(),配置合并用 array_merge_recursive()

若非作者标注皆为李涛自留地原创文章,转载或复制请以超链接形式并注明出处。