如何从 Laravel 中的数组中插入缺失的月份?

How to insert the missing months from an array in Laravel?

我这里有一个查询,当我尝试使用 dd($attr['month']) 时,每个 months 都有 returns status 这将 return 一个数组的,但正如我检查过的那样,它似乎缺少一些 months.

private function getSummaryData($seller)
{
    $query = json_decode(json_encode(DB::select(DB::raw("select user_id, 
    DATE_FORMAT(created_at, '%b %Y') ym,
    sum(IF(status='pending', 1, 0)) status_pending,
    sum(IF(status='success', 1, 0)) status_success
    FROM `case_summaries`
    WHERE user_id= " . $user->user->user_id . "
    GROUP BY DATE_FORMAT(created_at, '%b %Y')
    ORDER BY created_at asc "))), true);

    $attr = [];
    $attr['month'] = [];
    $attr['pending'] = [];
    $attr['success'] = [];

    foreach ($query as $key => $value) {
        array_push($attr['month'], $value['ym']);
        array_push($attr['pending'], $value['status_pending']);
        array_push($attr['success'], $value['status_success']);
    }

    dd($attr['month']);

    return $attr;
}

$attr['month']

数组的结果
^ array:24 [
  0 => "Feb 2018"
  1 => "Mar 2018"
  2 => "Apr 2018"
  3 => "May 2018"
  4 => "Jun 2018"
  5 => "Jul 2018"
  6 => "Aug 2018"
  7 => "Sep 2018"
  8 => "Oct 2018"
  9 => "Nov 2018"
  10 => "Dec 2018"
  11 => "Jan 2019"
  12 => "Feb 2019"
  13 => "Mar 2019"
  14 => "Apr 2019"
  15 => "May 2019"
  16 => "Jul 2019"
  17 => "Aug 2019"
  18 => "Sep 2019"
  19 => "Oct 2019"
  20 => "Nov 2019"
  21 => "Dec 2019"
  22 => "Jan 2020"
  23 => "Mar 2020"
]

正如您在此处看到的,它缺少月份 Jun 2019。如何添加 query?

中缺失的月份

我这里有这个功能,可以获取两个日期之间的所有月份

public function getMonthListFromDate(Carbon $date)
{
    $start    = new DateTime(); // Today date
    $end      = new DateTime($date->toDateTimeString()); // Create a datetime object from your Carbon object
    $interval = DateInterval::createFromDateString('1 month'); // 1 month interval
    $period   = new DatePeriod($start, $interval, $end); // Get a set of date beetween the 2 period
    $months = array();
    foreach ($period as $dt) {
        $months[] = $dt->format("F Y");
    }
    return $months;
}

关于如何在我的函数 getSummaryData() 中使用 foreach 循环实现此功能然后检查 if($attr['month'] == getMonthListFromDate()),我遇到了麻烦。将缺失的月份传递给我的 query 时如何添加?

我认为如果您的查询数据不符合要求,那么您可以根据您的要求生成完整的数组,例如

$months = [
    'Feb 2018',
    'Mar 2020',
];
$start_date = \Carbon\Carbon::parse($months[0]);
$end_date = \Carbon\Carbon::parse($months[array_key_last($months)]);

$months_diff = $start_date->diffInMonths($end_date);


if (count($months) != $months_diff) {
    $months = [$months[0]];
    $add_month = $start_date->addMonth();
    while ($add_month->lessThan($end_date)) {
        $months[] = $add_month->format('M Y');
        $add_month->addMonth();
    }
}