Jump to content

Sorting an array of dates


SCook

Recommended Posts

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

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);

?>

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>';
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.