Reputation: 1113
I have this array $primary_dates
, listing upcoming dates.
Two of them are in the past and one is in the future. I'd like to remove the past dates and only show the future date, based on today's date.
Array
(
[0] => Array
(
[event_date] => 2020-04-02 00:00:00 // PAST DATE
[event_start_time] => 09:20:00
[event_end_time] => 09:20:00
)
[1] => Array
(
[event_date] => 2020-04-07 00:00:00 // PAST DATE
[event_start_time] => 09:20:00
[event_end_time] => 09:20:00
)
[2] => Array
(
[event_date] => 2020-12-18 00:00:00 // FUTURE DATE
[event_start_time] => 09:20:00
[event_end_time] => 09:20:00
)
)
Here's what I have. It partly works, $primary_dates
is reordered in reverse chronological order. Then if the first date in the array is older than $today_timestamp
I run unset
to remove the first array.
// GET THE CURRENT DATE
$timestamp = strtotime(date("Y-m-d"));
// SORT DATES IN REVERSE CHRONOLOGICAL ORDER
usort($item['event_dates_1'], function ($a, $b) {
return strtotime($a['event_date']) > strtotime($b['event_date']);
});
$primary_dates = $item['event_dates_1'];
$latest_date = strtotime($primary_dates[0]['event_date']);
if ($today_timestamp > $latest_date) {
unset($primary_dates[0]); // This removes the first date
print_r($primary_dates);
} else {
print_r($primary_dates);
}
When I run the code above the $primary_dates
array looks like this:
Array
(
[1] => Array
(
[event_date] => 2020-04-07 00:00:00 // PAST DATE
[event_start_time] => 09:20:00
[event_end_time] => 09:20:00
)
[2] => Array
(
[event_date] => 2020-12-18 00:00:00 // FUTURE DATE
[event_start_time] => 09:20:00
[event_end_time] => 09:20:00
)
)
Only the first date is removed, I understand why, I only unset the first array. I need all the past dates removed.
How do I loop over the array and remove all the past dates?
Upvotes: 1
Views: 325
Reputation: 688
You can do it by array_filter
like the following code:
$now = time();
$filteredEvents = array_filter(
$yourEventsArray,
function ($event) use ($now) {
return strtotime($event['event_date']) > $now;
}
);
Upvotes: 2