PHP的array_merge而不擦除值? [英] php array_merge without erasing values?

查看:142
本文介绍了PHP的array_merge而不擦除值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题:在默认情况下,PHP array_merge是这样的...它会覆盖一个空值非空值

Problem: by default, PHP array_merge works like this ... it will overwrite a non-blank value with a blank value.

$foobar   =   Array('firstname'=>'peter','age'=>'32','nation'=>'');
$feebar   =   Array('firstname' => '','lastname' => 'griffin', age =>'33','nation'=>'usa');

print_r(array_merge($foobar,$feebar));    
/*
Array
(
    [firstname] =>           // <-- feebar set this to blank, NOT COOL!
    [age] => 33              // <-- feebar set this to 33, thats cool
    [lastname] => griffin    // <-- feebar added this key-value pair, thats cool
    [nation] => usa          // <-- feebar filled in a blank, thats cool.
)
*/

问:什么是最少线-OF- code的方式做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($foobar,$feebar));    
/*
Array
(
    [firstname] => peter  // <-- don't blank out a value if one already exists!
    [age] => 33
    [lastname] => griffin
    [nation] => usa

)
*/

更新:我修改了原来的问题例子来阐明事情有点

UPDATE: I modified the original question example to clarify things a bit.

推荐答案

好吧,如果你想要一个聪明的方式来做到这一点,在这儿,但作为简单地做一个循环也未必为可读。

Well, if you want a "clever" way to do it, here it is, but it may not be as readable as simply doing a loop.

$merged = array_merge(array_filter($foo, 'strval'), array_filter($bar, 'strval'));

编辑:或使用+ ..​​.

edit: or using +...

这篇关于PHP的array_merge而不擦除值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆