douniang3866 2014-07-21 15:01
浏览 54
已采纳

array_merge()不会丢失空值

I have 2 arrays in PHP, one which simulates properties that can be edited, the other with the properties and the values it should have.

An example is as following:

$arr1 = array(
    'entity1' => array(
        'property1' => null,
        'property2' => null,
    ),
    'entity2' => array(
        'property3' => null,
        'property4' => null,
        'property5' => null,
    )
);
$arr2 = array(
    'entity1' => array(
        'property1' => 1,
        'property2' => 0,
    ),
    'entity2' => array(
        'property3' => 0,
        'property4' => 1,
    )
);

Now I need to merge these arrays and keep the null values, so that the output will be as following:

$output = array(
    'entity1' => array(
        'property1' => 1,
        'property2' => 0,
    ),
    'entity2' => array(
        'property3' => 0,
        'property4' => 1,
        'property5' => null,
    )
);

I tried array_merge() and $arr1 + $arr2 which both output this:

Array
(
    [entity1] => Array
        (
            [property1] => 1
            [property2] => 0
        )

    [entity2] => Array
        (
            [property3] => 0
            [property4] => 1
        )
)

The array can be deeper than displayed in the example, so it would have to be recursive, and the arrays are all associative.

I have read numerous questions on StackOverflow and Googled quite abit, but the answers I found are not recursive or just don't apply to this question.

EDIT

As above explanation for why I asked this question even though I checked other questions with answers is apparently not enough proof or something, I tried the marked duplicated questions answer, which is the following:

$merged = array_merge(array_filter($arr1, 'strval'), array_filter($arr2, 'strval'));

it gave an array to string conversion error cause it is not recursive, which is what I explained.

  • 写回答

2条回答 默认 最新

  • download2014711 2014-07-21 17:52
    关注

    This recursive function could be a starting point:

    function merge_associative($arr1, $arr2) {
      $merged = $arr1;
      foreach ($arr2 as $k => $v) {
        if (is_array($v) && is_array($arr1[$k]))
          $merged[$k] = merge_associative($arr1[$k], $v);
        else
          $merged[$k] = $v;
      }
      return $merged;
    }
    

    It will merge associative arrays, but can not handle numeric indices correctly.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥30 求解达问题(有红包)