[英]PHP array group by month and sum
假設第一個包含所有日期的數組稱為$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.