如何按月对数组中的值进行分组?

时间:2019-01-17 12:03:04

标签: php laravel laravel-5

我试图将特定键的所有值的总和添加到划分为数月的数组中,但无法弄清楚该如何做。我设法获得了第一个值,但是尝试添加到第一个值只会给我带来错误。

$accumulatedMonthly = DB::table('sold_tickets')
    ->select('price', 'created_at')
    ->where('event_id', $id)
    ->where('credited', null)
    ->where('user_id', '!=', null)
    ->orderBy('created_at')
    ->get()
    ->groupBy(function($val) {
        return Carbon::parse($val->created_at)->format('M y');
    });

$accumulatedMonthly = json_decode(json_encode($accumulatedMonthly), true);
$accumulatedPerMonth = [];

foreach ($accumulatedMonthly as $k => $month) {
    foreach ($month as $m) {
        $accumulatedPerMonth[$k] = $m['price'];
    }
}

我希望将结果分成几个月,并将所有“价格”值相加。现在,我可以正确获取月份,但是只有每个月的第一个值。

这是当前的输出

Array
(
    [Aug 16] => 999
    [Nov 16] => 1399
    [Dec 16] => 1399
    [Jan 17] => 1399
    [Feb 17] => 1599
    [Mar 17] => 1599
    [Apr 17] => 1599
    [May 17] => 1599
    [Jun 17] => 1599
    [Jul 17] => 1599
    [Aug 17] => 1199
)

3 个答案:

答案 0 :(得分:2)

更改

foreach ($accumulatedMonthly as $k => $month) {
    foreach ($month as $m) {
        $accumulatedPerMonth[$k] = $m['price'];
    }
}

至:

foreach ($accumulatedMonthly as $k => $month) {
    $accumulatedPerMonth[$k] = 0;
    foreach ($month as $m) {
        $accumulatedPerMonth[$k] += $m['price'];
    }
}

获得所有价格的总和。

答案 1 :(得分:1)

尝试收集采摘方法,您将获得数组数据。

更新,我已修改查询。

$accumulatedMonthly = DB::table('sold_tickets')
    ->select(DB::raw('SUM("price") as price'), DB::raw("date_format('created_at','%M %y') as month"))
    ->where('event_id', $id)
    ->where('credited', null)
    ->where('user_id', '!=', null)
    ->orderBy('created_at')
    ->get()
    ->groupBy(DB::raw("date_format('created_at','%M %y')"))->pluck('price','month');

答案 2 :(得分:0)

您可以执行以下操作:

    $accumulatedMonthly = DB::table('sold_tickets')
    ->select('price', 'created_at')
    ->where('event_id', $id)
    ->where('credited', null)
    ->where('user_id', '!=', null)
    ->orderBy('created_at')
    ->get();

     $accumulatedPerMonth = array();

     foreach ($accumulatedMonthly as $key => $value) 
     {
         if(array_key_exists(date('M y', strtotime($value->created_at)), $accumulatedPerMonth))
         {
             $accumulatedPerMonth[date('M y', strtotime($value->created_at))] += $value->price;  
         }
         else
         {
             $accumulatedPerMonth[date('M y', strtotime($value->created_at))] = $value->price; 
         }
     }