php array_merge 不删除值?

2021-12-27 00:00:00 merge arrays php

背景: 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);

这就是解决方案.

相关文章