PHP - 合并前一个数组缺失或存在但是空值的数组值

时间:2014-06-11 07:56:28

标签: php arrays merge

如何合并两个数组:

$arr1 = [1 => 'a', 2 => '', 3 => 'c'];
$arr2 = [1 => 'd', 2 => 'e', 3 => 'f'];

并获得:

[1 => 'a', 2 => 'e', 3 => 'c'];

我已经成功完成了:

$arr1 = [1 => 'a',           3 => 'c'];
$arr2 = [1 => 'd', 2 => 'e', 3 => 'f'];

$arr1 + $arr2;

但是,有时$ arr1也包含值2 => '',该值为空但存在,在这种情况下,2不会覆盖键$arr2

2 个答案:

答案 0 :(得分:0)

使用

  $arr1 = array(1 => 'a', 2 => '', 3 => 'c');
  $arr2 = array(1 => 'd', 2 => 'e', 3 => 'f');
  $arr3 = array_filter($arr1) + array_filter($arr2);
  print_r($arr3);

答案 1 :(得分:0)

$arr1 = array("a","","c");
$arr2 = array("d","e","f");

$i = 0;
foreach ($arr1 as $value) {
  if($arr1[$i] == "")
           $arr1[$i] = $arr2[$i];
  $i++;
}

print_r($arr1);

这里矩阵的维度和元素数量必须相等