通过其他子数组值相加多维子数组值

时间:2018-07-03 08:24:13

标签: php arrays multidimensional-array

我正在处理一个统计信息仪表板,我想在其中显示一些按日历周排序的统计信息。

我正在使用以下格式在多维数组中获取数据:

Array
(
   [success] => 1
   [stats] => Array
      (
        [0] => Array
            (
                [year] => 2018
                [week] => 14
                [sum] => 18
                [country] => at
            )

        [1] => Array
            (
                [year] => 2018
                [week] => 14
                [sum] => 907
                [country] => de
            )

        [2] => Array
            (
                [year] => 2018
                [week] => 15
                [sum] => 2
                [country] => 
            )

        [3] => Array
            (
                [year] => 2018
                [week] => 15
                [sum] => 65
                [country] => at
            )

        [4] => Array
            (
                [year] => 2018
                [week] => 15
                [sum] => 237
                [country] => de
            )
        )

     )

我的问题是,不仅要按日历周分组,还要按国家/地区分组。我要获取的是一个数组,该数组按日历周分组。 sum应该是同一周的每个sum值的总和。 我需要的数组应如下所示:

Array
(
   [success] => 1
   [stats] => Array
     (
        [0] => Array
            (
                [year] => 2018
                [week] => 14
                [sum] => 925
            )

        [1] => Array
            (
                [year] => 2018
                [week] => 15
                [sum] => 304
            )

       )

  )

country不再需要,每个日历周应只有1个条目。

1 个答案:

答案 0 :(得分:1)

类似的事情应该可以解决问题

$newArray = [];
foreach ($firstArray['stats'] as $entry) {
    if (isset($newArray[sprintf('%d-%d', $entry['year'], $entry['week'])])) {
        $newArray[sprintf('%d-%d', $entry['year'], $entry['week'])]['sum'] += $entry['sum'];
    } else {
        $newArray[sprintf('%d-%d', $entry['year'], $entry['week'])] = $entry;
    }
}

编辑

$newArray = [];

foreach ($stats['stats'] as $entry) {
   if (isset($newArray[sprintf('%d-%d', $entry['year'], $entry['week'])])) {
     $newArray[sprintf('%d-%d', $entry['year'], $entry['week'])]['sum'] += 
     $entry['sum'];
   } else {
     $newArray[sprintf('%d-%d', $entry['year'], $entry['week'])] = $entry;
   }
   unset($newArray[sprintf('%d-%d', $entry['year'], $entry['week'])]['country']);

}

$stats['stats'] = array_values($newArray);

@Rok D.谢谢您……我可以改编您的例子以完全满足我的需求。