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

Link to comment
Share on other sites

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

Link to comment
Share on other sites

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.