我在这里有一个查询,当我尝试使用dd($attr['month'])
时,我为每个months
返回status
,这将返回这个数组,但正如我所检查的,它似乎有一些缺失的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 = CarbonCarbon::parse($months[0]); $end_date = CarbonCarbon::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(); } }