문제

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.

도움이 되었습니까?

해결책

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

다른 팁

You can use usort:

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

usort($allarticles, 'csort');

DEMO

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

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;
});
$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.

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

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top