How to sort an array by date it was created

530 Views Asked by At

I have an array of articles.

 $allarticles = Array ([0] => Array ([id] => 24,
                                     [article_id] => 74,
                                     [created] => 2011-01-01 20:48:48 ) 
                       [1] => Array ( [id] => 39,
                                      [article_id] => 94,
                                      [created] => 2011-02-21 21:06:44 ) 
                      );     

I would like to sort the array by the created date(DESC most recent first).

I appreciate any help.

Thanks.

7

There are 7 best solutions below

0
OldWest On BEST ANSWER

You might be able to use the CakePHP static Set::sort method here.

2
adarshr On

http://www.php.net/manual/en/function.uasort.php

uasort($allarticles, function ($a, $b) {
    $diff = 
    /*
    write code here to convert the string dates to numeric equivalents and subtract them. 
    If you want to reverse the order, revers the way you subtract.
    */
    return $diff;
});
0
hsz On
$sortedArticles = array();
foreach ( $allarticles as $article ) {
    $timestamp = strtotime($article ['created']);
    $sortedArticles[$timestamp] = $article;
}
ksort($sortedArticles);

var_dump($sortedArticles);

Or when you fetch data from database just do ORDER BY created.

1
Jon On
uasort($allarticles, 'sort_by_date');
function sort_by_date($a, $b) {
    if (strtotime($a['created']) == strtotime($b['created'])) {
        return 0;
    }
    return strtotime($a['created') > strtotime($b['created']) ? 1 : -1;
}
2
Brad Christie On

I believe you're looking for usort.

function sortbycreated($a,$b){
  return ($a['created']>$b['created']?1:($a['created']<$b['created']?-1:0));
}
usort($allarticles,'sortbycreated');

Still waking up, so if that sorts in the reverse order, swap the 1 and -1. Also, this assumes the dats are actual "time()"s. If they aren't you'll need to parse to a value you can compare before you check, but all this can be done in the new function.

EDIT

If they aren't already time()s:

function sortbycreated($a,$b){
  $_a = strtotime($a['created']); $_b = strtotime($b['created']);
  return ($_a > $_b ? 1 : ($_a < $_b ? -1 : 0));
}
2
Felix Kling On

You can use usort:

function csort($a, $b) {
    return strcmp($b['created'], $a['created']);
}

usort($allarticles, 'csort');

DEMO

0
Nik Chankov On

Probably it's better to sort this within the database instead. For me it's useless to make iterations of something which will be served from the database for free.

In case you are interested. You just have to do this:

$this->YourModel->find('all', array('order'=>'created'));

otherwise just use one of other solutions proposed in the tread.