合并多个二维关联数组,填充缺失列的默认值并对相交列值求和

问题描述 投票:0回答:2

我有 3 个数组,表示按日期分组的数据计数

$dummyArray1 = array('year' => array('month' => 'count'));

$dummyArray1 = array(
    '2012' => array(
        '1' => 13,
        '2' => 22,
        '3' => 18,
        '5' => 19
     ),
    '2011' => array(
        '1' => '4',
        '3' => 13
     )
);

$dummyArray2 = array(
    '2012' => array(
        '1' => 44,
        '4' => 34,
        '5' => 38,
        '6' => 29
     ),
    '2011' => array(
        '1' => 9,
        '2' => 11,
        '3' => 1
     )
);

$dummyArray3 = array(
    '2012' => array(
        '2' => 5,
        '4' => 3,
        '6' => 1,
        '8' => 11
     ),
    '2011' => array(
        '3' => 9,
        '4' => 14,
        '9' => 9
     )
);

我需要将它们分组到 1 个数组中,这样每个月我都会有每个数组的

count
值。如果特定月份不存在计数数据,则应插入
0
作为
count
值。

所需输出:

[
  2012 => [
    1 => 57,
    2 => 27,
    3 => 18,
    4 => 37,
    5 => 57,
    6 => 30,
    7 => 0,
    8 => 11,
    9 => 0,
    10 => 0,
    11 => 0,
    12 => 0,
  ],
  2011 => [
    1 => 13,
    2 => 11,
    3 => 23,
    4 => 14,
    5 => 0,
    6 => 0,
    7 => 0,
    8 => 0,
    9 => 9,
    10 => 0,
    11 => 0,
    12 => 0,
  ],
]
php arrays multidimensional-array sum merging-data
2个回答
1
投票

如果你创建一个函数会更容易:

<?php

function groupMyArray($dummysArray)
{
   $result = array();
   foreach($dummysArray as $dummyArray):
      foreach($dummyArray as $year => $countarray):
          for($i = 1; $i <= 12; $i++):
              if(count($countarray[$i]) > 0){
                  $result[$year] = array($i => $countarray[$i]);
              }else{
                  $result[$year] = array($i => 0);
              }
          endfor;
      endforeach;
   endforeach;

   return $result;
}

好的,知道你必须构造 $dummyArray:

$dummyArray = array(
    $dummyArray1,
    $dummyArray2,
    $dummyArray3
);


$dummyArraygroup = groupMyArray($dummyArray);

?>


0
投票

无需在每个输入数组中每年运行 12 项循环,只需声明一个零值元素数组作为每年的基础即可。然后仅迭代每年的实际月份元素并在需要时求和。 演示

$defaults = array_fill_keys(range(1, 12), 0);
$result = [];
foreach ([$array1, $array2, $array3] as $array) {
    foreach ($array as $year => $row) {
        $result[$year] ??= $defaults;
        foreach ($row as $month => $v) {
            $result[$year][$month] += $v;
        }
    }
}
var_export($result);

输出:

array (
  2012 => 
  array (
    1 => 57,
    2 => 27,
    3 => 18,
    4 => 37,
    5 => 57,
    6 => 30,
    7 => 0,
    8 => 11,
    9 => 0,
    10 => 0,
    11 => 0,
    12 => 0,
  ),
  2011 => 
  array (
    1 => 13,
    2 => 11,
    3 => 23,
    4 => 14,
    5 => 0,
    6 => 0,
    7 => 0,
    8 => 0,
    9 => 9,
    10 => 0,
    11 => 0,
    12 => 0,
  ),
)
© www.soinside.com 2019 - 2024. All rights reserved.