php array_merge without erasing values?
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.
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.
)
*/
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
)
*/
UPDATE: 2016-06-17T11:51:54 the question was updated with clarifying context and rename of variables.
如果你对这篇文章有疑问,欢迎到本站 社区 发帖提问或使用手Q扫描下方二维码加群参与讨论,获取更多帮助。

评论(6)


This will put duplicates into a new array, I don't know if this is what you want though.
<?php
$foobar = Array('firstname' => 'peter','age' => '33',);
$feebar = Array('firstname' => '','lastname' => 'griffin',);
$merged=$foobar;
foreach($feebar as $k=>$v){
if(isset($foobar[$k]))$merged[$k]=array($v,$foobar[$k]);
else $merged[$k]=$v;
}
print_r($merged);
?>
This will simply assure that feebar will never blank out a value in foobar:
<?php
$foobar = Array('firstname' => 'peter','age' => '33',);
$feebar = Array('firstname' => '','lastname' => 'griffin',);
$merged=$foobar;
foreach($feebar as $k=>$v) if($v)$merged[$k]=$v;
print_r($merged);
?>
or ofcourse,
<?
function cool_merge($array1,$array2){
$result=$array1;
foreach($array2 as $k=>$v) if($v)$result[$k]=$v;
return $result;
}
$foobar = Array('firstname' => 'peter','age' => '33',);
$feebar = Array('firstname' => '','lastname' => 'griffin',);
print_r(cool_merge($foobar,$feebar));
?>


发布评论
需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。