問題描述
背景: Trevor 正在使用標(biāo)準(zhǔn)算法的 PHP 實(shí)現(xiàn):采用一組主要的默認(rèn)名稱-值對(duì),并更新這些名稱-值對(duì),但僅限于那些名稱-值實(shí)際存在有效更新值的對(duì).
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.
問題:默認(rèn)情況下,PHP array_merge 是這樣工作的......它會(huì)用一個(gè)空值覆蓋一個(gè)非空值.
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.
)
*/
問題:在空值永遠(yuǎn)不會(huì)覆蓋現(xiàn)有值的情況下,執(zhí)行 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);
這就是解決方案.
這篇關(guān)于php array_merge 不刪除值?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!