PHP array_merge_recursive() 和 array_replace() 详解:数组合并与替换
- 2026年7月3日
- 219 次
前言
合并数组时 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);
}
?>
踩坑提醒
- array_merge_recursive() 会递归合并,可能导致意外的深层数组
- array_replace() 不存在的键不会被添加
- array_merge_recursive() 相同键名会创建嵌套数组,注意后续处理
总结
- array_merge_recursive() 用于配置合并,相同键值合并为数组
- array_replace() 用于默认值覆盖,保持默认值结构
- 简单合并用 array_merge(),配置合并用 array_merge_recursive()
<?php
$defaults = ['database' => ['host' => 'localhost', 'port' => 3306], 'cache' => ['enabled' => true]];
$userConfig = ['database' => ['host' => 'db.example.com']];
$config = array_merge_recursive($defaults, $userConfig);
?>
<?php
function getSettings($userSettings) {
$defaults = ['theme' => 'light', 'lang' => 'zh', 'notify' => true];
return array_replace($defaults, $userSettings);
}
?>
踩坑提醒
- array_merge_recursive() 会递归合并,可能导致意外的深层数组
- array_replace() 不存在的键不会被添加
- array_merge_recursive() 相同键名会创建嵌套数组,注意后续处理
总结
- array_merge_recursive() 用于配置合并,相同键值合并为数组
- array_replace() 用于默认值覆盖,保持默认值结构
- 简单合并用 array_merge(),配置合并用 array_merge_recursive()
若非作者标注皆为李涛自留地原创文章,转载或复制请以超链接形式并注明出处。
- 上一篇: PHP array_key_first() 和 array_key_last():获取数组首尾键名
- 下一篇: PHP 数组查找函数 in_array()、array_search()、array_keys() 实战对比
- text-indent在Css中有什么作用?text-indent怎么使用? 2022-10-30
- IT男的兴奋点是什么? 2021-01-03
- PHP中正则表达式修正符有哪些?PHP正则表达式修正符如何使用 2022-10-31
- PHP array_reverse() 函数详解:数组反转的 N 种方式 2026-07-02
- PHP日期函数mktime()如何使用 PHP时间函数mktime()实例代码 2022-10-15
- PHP常用字符串函数分割与合并字符串函数用法及实例 2022-11-10
