Как сгруппировать значения в массиве по месяцам? - PullRequest
0 голосов
/ 17 января 2019

Я пытаюсь добавить сумму всех значений определенного ключа в массив, разделенный на месяцы, но не могу понять, как это сделать. Мне удается получить первое значение, но попытка добавить к этому только дает мне ошибки.

$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 голосов
/ 17 января 2019

попробуйте метод сбора данных, у вас будут данные массива.

обновление Я изменил запрос.

$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 голосов
/ 17 января 2019

Вы можете сделать что-то вроде этого:

    $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; 
         }
     }
0 голосов
/ 17 января 2019

Изменение

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'];
    }
}

чтобы получить сумму всех цен.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...