I am trying to create a function that get the last seven days date and count the common date.
Something like this
column1 column2
10/28/2020 5
10/27/2020 0
10/26/2020 6
10/25/2020 2
10/24/2020 1
10/23/2020 0
10/22/2020 2
but when getting the date of last seven days the date getting off.
This is the code:
$today = Carbon::today();
$date_array = array();
$date_count = array();
$i = 0;
while ($i < 7) {
array_push( $date_array, $today->subDays($i)->format('Y-m-d H:i:s') );
$i++;
}
if(! empty( $date_array ) ){
foreach($date_array as $date){
$date_count = CampaignHistory::where( 'created_at', '>', $date )->get()->count();
}
}
echo json_encode($date_array );
In place of assigning today in start put it under the loop so that every time it initializes again to the current date when you sub day for $today
it becomes
$today = $day-$i;
$date_array = array();
$date_count = array();
$i = 0;
while ($i < 7) {
$today = Carbon::today();
array_push( $date_array, $today->subDays($i)->format('Y-m-d H:i:s') );
$i++;
}
if(! empty( $date_array ) ){
foreach($date_array as $date){
$date_count = CampaignHistory::where( 'created_at', '>', $date )->get()->count();
}
}
echo json_encode($date_array );