Jump to content

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.