合并嵌套数组元素

时间:2016-10-13 11:39:56

标签: php arrays

如何转换此数组结果;

array (size=2)
  0 => 
    array (size=6)
      'processed' => int 7
      'committed' => int 0
      'merged' => int 6
      'updated' => int 0
      'skipped' => int 1
      'ids' => 
        array (size=6)
          '57ff644ab0e6df8a148b45c7' => string 'merged' (length=6)
          '57ff644ab0e6df8a148b45c9' => string 'merged' (length=6)
          '57ff644ab0e6df8a148b45ca' => string 'merged' (length=6)
          '57ff644ab0e6df8a148b45cb' => string 'merged' (length=6)
          '57ff644ab0e6df8a148b45cc' => string 'merged' (length=6)
          '57ff644bb0e6df8a148b45cd' => string 'merged' (length=6)
  1 => 
    array (size=6)
      'processed' => int 6
      'committed' => int 0
      'merged' => int 4
      'updated' => int 0
      'skipped' => int 2
      'ids' => 
        array (size=5)
          '57ff644cb0e6df98148b4574' => string 'merged' (length=6)
          '57ff644cb0e6df98148b4575' => string 'merged' (length=6)
          '57ff644cb0e6df98148b4576' => string 'merged' (length=6)
          '57ff644cb0e6df98148b4578' => string 'merged' (length=6)
          '57ff644cb0e6df98148b4579' => string 'skipped' (length=7)

在这样的事情上;

array (size=1)
  0 => 
    array (size=6)
      'processed' => int 13
      'committed' => int 0
      'merged' => int 12
      'updated' => int 0
      'skipped' => int 1
      'ids' => 
        array (size=13)
          '57ff644ab0e6df8a148b45c7' => string 'merged' (length=6)
          '57ff644ab0e6df8a148b45c9' => string 'merged' (length=6)
          '57ff644ab0e6df8a148b45ca' => string 'merged' (length=6)
          '57ff644ab0e6df8a148b45cb' => string 'merged' (length=6)
          '57ff644ab0e6df8a148b45cc' => string 'merged' (length=6)
          '57ff644bb0e6df8a148b45cd' => string 'merged' (length=6)
          '57ff644cb0e6df98148b4574' => string 'merged' (length=6)
          '57ff644cb0e6df98148b4575' => string 'merged' (length=6)
          '57ff644cb0e6df98148b4576' => string 'merged' (length=6)
          '57ff644cb0e6df98148b4578' => string 'merged' (length=6)
          '57ff644cb0e6df98148b4579' => string 'skipped' (length=7)

就像每个元素上的合并一样。

我试过了;

foreach ($array as $key => $value) {
    $new = array_merge_recursive($blah[$key]);
}

还有其他一些令人费解的方法,但我无法实现。

1 个答案:

答案 0 :(得分:1)

您可以使用array_reduce之类的:

$finalArray = array_reduce($myArray, function($carry, $item) {

    foreach ($item as $key => $value) {
        if (!isset($carry[$key])) {
            $carry[$key] = $value;
            continue;
        }
        if (is_array($value)) {
            $carry[$key] = array_merge($carry[$key], $value);
        } else {
            $carry[$key] += $value;
        }
    }

    return $carry;
}, []);