繁体   English   中英

PHP 数组按月和总和分组

[英]PHP array group by month and sum

我有一个 php 阵列,如第一张图片所示。

分组和求和前的数组

我想要的只是按月获取总和组值,如此处所示。

数组求和并按月分组

我知道这对我们大多数人来说可能很容易,但老实说,我找不到一种可行的方法来实现它。

我尝试在谷歌上搜索,但我发现的所有结果都是关于对数据库查询结果进行分组和求和,而对我来说,我手中的数组是一个数组。

请告诉我正确的 function。 谢谢你。

假设第一个包含所有日期的数组称为$dates

$datesGroup = array();
foreach($dates as $date=>$value) $datesGroup[date('M Y', strtotime($date))]=( $datesGroup[date('M Y', strtotime($date))] ?? 0 )+$value;

算法很简单:遍历数组,然后增加日期 function 产生的正确索引

好的,我认为这正是您想要的。

$datewise_data = array
(
    '2019-09-13' => 3,
    '2019-09-14' => 1,
    '2019-08-21' => 2,
    '2019-08-03' => 1,
    '2019-10-10' => 3,
    '2019-10-15' => 3,
    '2020-02-15' => 3,
    '2020-01-14' => 4,
    '2020-02-17' => 7,
    '2020-01-03' => 2
);

$monthwise_data = array();

foreach($datewise_data as $key => $value){
    
    $month_key = date('Y-m', strtotime($key));
    
    if(array_key_exists($month_key, $monthwise_data)){

        // If we've already added this month to the new array, add the value
        $monthwise_data[$month_key] += $value;
    }
    else{

        // Otherwise create a new element with month as key and store the value
        $monthwise_data[$month_key] = $value;
    }
}
 

// Can also use ksort() function if needed here
ksort($monthwise_data); // ksort() function sorts an associative array in ascending order, according to the key

// Adjusting array as per your requirement
foreach($monthwise_data as $key => $value){
    $resultant_array[date('M Y', strtotime($key))] = $value;
}

print_r($resultant_array);

//Output
//Array ( [Aug 2019] => 3 [Sep 2019] => 4 [Oct 2019] => 6 [Jan 2020] => 6 [Feb 2020] => 10 ) 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM