【问题标题】:How to sort an array by date it was created如何按创建日期对数组进行排序
【发布时间】:2011-07-02 01:38:24
【问题描述】:

我有很多文章。

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

我想按创建日期对数组进行排序(DESC 最近在前)。

感谢您的帮助。

谢谢。

【问题讨论】:

标签: php sorting asort


【解决方案1】:

你可以使用usort:

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

usort($allarticles, 'csort');

DEMO

【讨论】:

  • strcmp 是否适用于日期?我想只是按照信息的顺序,它会起作用,对吧?
  • @Brad Christie:是的,在这种情况下它可以工作,因为日期的格式。
【解决方案2】:

我相信你正在寻找usort

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

仍在醒来,因此如果以相反的顺序排序,请交换 1-1。此外,这假设数据是实际的“时间()”。如果不是,则需要在检查之前解析为可以比较的值,但所有这些都可以在新函数中完成。

编辑

如果他们还不是time()s:

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

【讨论】:

  • 您应该将 sortbycreated 作为字符串传递给 usort ;)(没有它也可以工作,但您会收到有关未定义常量的通知)。
  • @FelixKling:很好,我一直在 C#、JavaScript 和 PHP 之间徘徊。 ;p 感谢您的提醒。
【解决方案3】:

您也许可以使用 CakePHP 的静态 Set::sort 方法here

【讨论】:

    【解决方案4】:

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

    【讨论】:

    • 你应该提到这只适用于 PHP 5.3 及更高版本。
    • 不,它甚至适用于 PHP 4。至少 PHP 手册是这么说的!
    【解决方案5】:
    $sortedArticles = array();
    foreach ( $allarticles as $article ) {
        $timestamp = strtotime($article ['created']);
        $sortedArticles[$timestamp] = $article;
    }
    ksort($sortedArticles);
    
    var_dump($sortedArticles);
    

    或者当您从数据库中获取数据时,只需执行ORDER BY created

    【讨论】:

      【解决方案6】:
      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;
      }
      

      【讨论】:

      • 您真的需要strtotime 来查看它们是否相同吗?
      【解决方案7】:

      也许最好在数据库中进行排序。对我来说,对从数据库免费提供的东西进行迭代是没有用的。

      如果您有兴趣。你只需要这样做:

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

      否则只需使用胎面中提出的其他解决方案之一。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-11-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-10-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多