Created
November 27, 2014 12:42
-
-
Save poly-glot/9d40bacdf48ed9398a89 to your computer and use it in GitHub Desktop.
PHP Sort Array by Date
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
header('content-type: text/plain'); | |
//Creating Test Data | |
$event_listing = array(); | |
$event_listing[] = array('event_name' => 'WordPress Meetup', 'event_date' => '2015-03-02'); | |
$event_listing[] = array('event_name' => 'Dribbble Meetup', 'event_date' => '2014-09-23'); | |
$event_listing[] = array('event_name' => 'Behance Meetup', 'event_date' => '2014-12-17'); | |
//Creating UNIX Timestamp so we can apply sort and filter | |
$event_listing = array_map(function($event) | |
{ | |
$event['timestamp'] = strtotime($event['event_date']); | |
$event['event_date_display'] = date('D d M, Y', $event['timestamp']); | |
return $event; | |
}, $event_listing); | |
//Remove past events | |
$today = mktime(0, 0, 0); | |
$event_listing = array_filter($event_listing, function($event) use($today) | |
{ | |
return ($event['timestamp'] >= $today); | |
}); | |
//Get all dates so we can sort | |
$event_timestamps = array_map(function($event) { return $event['timestamp']; }, $event_listing); | |
array_multisort($event_timestamps, SORT_ASC, SORT_NUMERIC, $event_listing); | |
//Display Events now | |
foreach($event_listing as $event) | |
{ | |
echo $event['event_name'] . " on ". $event['event_date_display'] . PHP_EOL; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment