簡體   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