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

问题描述 投票:2回答:3

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

$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
)
php laravel laravel-5
3个回答
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
投票

尝试收集pluck方法,你将拥有数组数据。

更新我已修改查询。

$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');

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; 
         }
     }
© www.soinside.com 2019 - 2024. All rights reserved.