php array_merge without erasing values?(php array_merge 不删除值?)
问题描述
背景: Trevor 正在使用标准算法的 PHP 实现:采用一组主要的默认名称-值对,并更新这些名称-值对,但仅限于那些名称-值实际存在有效更新值的对.
Background: Trevor is working with a PHP implementation of a standard algorithm: take a main set of default name-value pairs, and update those name-value pairs, but only for those name-value pairs where a valid update value actually exists.
问题:默认情况下,PHP array_merge 是这样工作的......它会用一个空值覆盖一个非空值.
Problem: by default, PHP array_merge works like this ... it will overwrite a non-blank value with a blank value.
$aamain = Array('firstname'=>'peter','age'=>'32','nation'=>'');
$update = Array('firstname' => '','lastname' => 'griffin', age =>'33','nation'=>'usa');
print_r(array_merge($aamain,$update));
/*
Array
(
[firstname] => // <-- update set this to blank, NOT COOL!
[age] => 33 // <-- update set this to 33, thats cool
[lastname] => griffin // <-- update added this key-value pair, thats cool
[nation] => usa // <-- update filled in a blank, thats cool.
)
*/
问题:在空值永远不会覆盖现有值的情况下,执行 array_merge 的最少代码行方式是什么?
Question: What's the fewest-lines-of-code way to do array_merge where blank values never overwrite already-existing values?
print_r(array_coolmerge($aamain,$update));
/*
Array
(
[firstname] => peter // <-- don't blank out a value if one already exists!
[age] => 33
[lastname] => griffin
[nation] => usa
)
*/
更新: 2016-06-17T11:51:54 更新了问题,澄清了上下文和变量重命名.
UPDATE: 2016-06-17T11:51:54 the question was updated with clarifying context and rename of variables.
推荐答案
array_replace_recursive($array, $array2);
这就是解决方案.
这篇关于php array_merge 不删除值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:php array_merge 不删除值?
基础教程推荐
- PHP 类:全局变量作为类中的属性 2021-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- 如何替换eregi() 2022-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
