I have here a query that I have returns status
for each months
when I try to use dd($attr['month'])
this will return an array of this but as what I've checked it seems that it has some missing 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;
}
Result of Array for $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"
]
As you can see here that it has a missing month which is Jun 2019
. How I can I add the missing months of the query
?
I have this function here that getting all months between 2 dates
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;
}
I'm having trouble here on how to implement this using foreach
loop in my function getSummaryData()
and then checks if($attr['month'] == getMonthListFromDate())
. How can I add those missing months when passing them to my query
?
I think if your query data is not as required then you can generate complete array as per your requirements like
$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(); } }