SCook Posted July 17, 2007 Share Posted July 17, 2007 Hello, I have an array of dates formatted like: 7/17/2007, now I want to sort them from the most current date tot he furtherest from now, and let's say the array is like this: dates[0] = 7/17/2007 dates[1] = 7/22/2007 datesp2] = 6/22/2007 dates[3] = 2/22/2008 Now, a standard sort() will not work, because it sorts from the beginning of each string. Any suggestions? Or an inherit function that might help? Thanks. Link to comment https://forums.phpfreaks.com/topic/60410-sorting-an-array-of-dates/ Share on other sites More sharing options...
Caesar Posted July 17, 2007 Share Posted July 17, 2007 Convert them all to timestamps then use usort(). Only format dates for display purposes...there's not much benefit to saving them as formatted dates. Will make life easier when it's time to do comparisons or use them in different manners. Link to comment https://forums.phpfreaks.com/topic/60410-sorting-an-array-of-dates/#findComment-300519 Share on other sites More sharing options...
sasa Posted July 17, 2007 Share Posted July 17, 2007 try <?php function my_dsort($a, $b){ $a = explode('/',$a); $b = explode('/',$b); if ($a[2] > $b[2]) return 1; if ($a[2] < $b[2]) return -1; if ($a[1] > $b[1]) return 1; if ($a[1] < $b[1]) return -1; if ($a[0] > $b[0]) return 1; if ($a[0] < $b[0]) return -1; return 0; } $dates[0] = '7/17/2007'; $dates[1] = '7/22/2007'; $dates[2] = '6/22/2007'; $dates[3] = '2/22/2008'; shuffle($dates); print_r($dates); usort($dates, 'my_dsort'); print_r($dates); ?> Link to comment https://forums.phpfreaks.com/topic/60410-sorting-an-array-of-dates/#findComment-300530 Share on other sites More sharing options...
Barand Posted July 17, 2007 Share Posted July 17, 2007 Slightly easier is <?php $dates[0] = '7/17/2007'; $dates[1] = '7/22/2007'; $dates[2] = '6/22/2007'; $dates[3] = '2/22/2008'; function mysort($a,$b) { $aa = date('Y-m-d',strtotime($a)); $bb = date('Y-m-d',strtotime($b)); return strcmp($aa, $bb); } usort($dates, 'mysort'); /** * check */ echo '<pre>', print_r($dates, true), '</pre>'; ?> Link to comment https://forums.phpfreaks.com/topic/60410-sorting-an-array-of-dates/#findComment-300537 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.