【问题标题】:sort an Array of dates from the smallest date on php [duplicate]从php上的最小日期对日期数组进行排序[重复]
【发布时间】:2018-06-23 13:46:10
【问题描述】:

我需要从最小的日期开始对数组进行排序。我使用了 Usort,但它只考虑当天对数组进行排序。我尝试使用在 javascript 中使用排序的示例中的代码,但我需要在 php 中发生这种情况或找到将 php 数组转换为 js 的方法。

代码如下:

<?php
          ArrayDates ( [0] => 22/03/2018 [1] => 09/04/2018 [2] => 26/03/2018 
          [3] => 27/11/2017 [4] => 22/01/2018 [5] => 06/09/2017 )
?>
           <script>
           ArrayDates.sort(function (a, b){
                var aa = a.split('-'),
                    bb = b.split('-');

                return aa[2] - bb[2] || aa[1] - bb[1] || aa[0] - bb[0];
            })
          </script>

【问题讨论】:

  • 如果你格式化你的日期properly,那么你就可以strcmp他们。如果您使用时间戳会更好,因为这些只是您可以直接排序的数字。输出结果给用户时只使用D/M/Y格式。
  • 看起来您使用了 Javascript 中的示例。这不是有效的 PHP 代码。
  • 是的,这可能是 javascript。仅缺少分号...
  • 那个数组定义非常奇怪。看起来像 print_r 输出而不是实际的数组。
  • 嗨,是的,数组来自 print_r,我把它作为例子。日期格式为西班牙方式,我需要保持这种方式。正如 rickdenhaad 所说,我刚刚意识到这是一个 Javascript 示例。

标签: php arrays sorting date


【解决方案1】:

您好,我终于在论坛中找到了解决方案,也许可以对其他人有所帮助。解决方案是基于原始数组创建一个新的时间戳数组。然后对这个新数组进行排序。使用“日期”回显新数组的第一个元素后,将返回第一个日期。代码如下:

  <?php
            $ArrayDates= array ('22/03/2018','09/04/2018', '26/03/2018', 
            '27/11/2017','22/01/2018', '06/09/2017');

            function date_to_timestamp($d){
                $newarr = array();
                foreach($d as $f) {
                $arr=explode("/",$f);
                array_push($newarr, mktime(0,0,0,$arr[0],$arr[1],$arr[2]));
                }

                return $newarr;
            } 

            function cmp2($a, $b)
                {
                if ($a == $b) {
                return 0;
                }
                return ($a < $b) ? -1 : 1;
            }

            $third = date_to_timestamp($ArrayDates);

            usort($third, "cmp2");

            echo date('m/d/Y', $third[0]);
  ?>

【讨论】:

  • 您的cmp2 功能很糟糕,甚至不需要。只需使用usort($third, "strcmp"); 并完全删除cmp2
【解决方案2】:

这将按升序对日期数组进行排序。

$date = array('23-02-2012','21-01-2014','11-01-2010','09-02-2001','01-01-2019');  

function date_sort($a, $b) {
    return strtotime($a) - strtotime($b);
}

usort($date, "date_sort");

print_r($date);

输出:-

Array ( 
         [0] => 09-02-2001 
         [1] => 11-01-2010 
         [2] => 23-02-2012 
         [3] => 21-01-2014 
         [4] => 01-01-2019 
      )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-25
    • 1970-01-01
    • 2017-06-13
    • 1970-01-01
    • 2011-02-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多