如何实现以下目标?
$array1 = array( id => '11', c1 => 'abcd', c2 => '4500', c3 => 'texas' ,c4=>'name' );
$array2 = array( id => '12', c1 => '', c2 => '4500', c3 => 'arizona', c4=>'' );
我希望比较数组1和数组2,并在数组2值为null
时将值从数组1复制到数组2。上面的数组示例我想只复制c1& c4键从数组1到数组2。
感谢您的帮助
答案 0 :(得分:4)
foreach()
循环怎么样:
foreach($array1 as $key=>$value){
if(!$array2[$key]){
$array2[$key] = $value;
}
}
最小化,但可读性稍差:
foreach($array1 as $key=>$value){
$array2[$key] = $array2[$key] ? $array2[$key] : $value;
}
答案 1 :(得分:0)
试试这个:
foreach($array2 as $key=>$value)
if ($value==null) $array2[$key]=$array1[$key];
答案 2 :(得分:0)
试试这个
<?php
$array1 = array( id => '11', c1 => 'abcd', c2 => '4500', c3 => 'texas' ,c4=>'name' );
$array2 = array( id => '12', c1 => '', c2 => '4500', c3 => 'arizona', c4=>'' );
foreach($array2 as $key =>$value)
{
if($value == '')
{
$array2[$key] = $array1[$key];
}
}
print_r($array2);
?>