Jump to content

[SOLVED] sort array by date


bigtimslim

Recommended Posts

You should indeed use the standard YYYY-MM-DD.

 

However, you could stick with British date formatting, and convert to ISO format.  Say you had an array that was just dates, e.g.

 

$DateArray = array();
$DateArray[] = "04-10-2007";
$DateArray[] = "15-06-2008";
$DateArray[] = "07-02-2008";
$DateArray[] = "22-01-2007";
$DateArray[] = "14-07-1987";

 

You could create a function to convert the date....

 

function SortDate($a, $b)
{
list($x, $y, $z) = explode("-", $a); 
$a = "$z-$y-$x";
list($x, $y, $z) = explode("-", $b);
$b = "$z-$y-$x";
return -strcmp($a, $b);
}

 

and sort the array using the function...

 

usort($DateArray, 'SortDate');

 

*EDIT* Apologies if you just read that, I failed to take into account that you wanted the most recent date first.  I have changed the code to -strcmp in order to do this (without the - it would have listed oldest date first).

if date is in the first position you can just use rsort()

 

<?php
$array = array  (
             0 =>      array ('2008-03-25', 'title 3', 'description 3', 'link 3'),
             1 =>      array ('2008-02-03', 'title 4', 'description 4', 'link 4'),
             2 =>      array ('2008-01-22', 'title 5', 'description 5', 'link 5'),
             3 =>      array ('2008-04-23', 'title 1', 'description 1', 'link 1'),
             4 =>      array ('2008-04-01', 'title 2', 'description 2', 'link 2'),
             );
                
rsort($array);

echo '<pre>', print_r($array, 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.