【问题标题】:Trying to order an array by minutes remaining尝试按剩余分钟数订购阵列
【发布时间】:2014-07-23 13:48:04
【问题描述】:

我有一个数据数组,我想根据当前时间与我为数组中的每个项目存储的日期戳值之间的时间差对该数组进行排序。

例如,现在时间是 14:47:57,我的数组可能有以下时间:

23:00:00 00:30:00 19:00:00 20:30:00 00:00:00

排序时,我希望数组按以下顺序排列(最接近当前时间的优先 - 但是时间总是要向前)

19:00:00 20:30:00 23:00:00 00:00:00 00:30:00

关于我需要看什么的任何建议?从数据库中获取值时,我查看了 TIMESTAMPDIFF,但得到的结果不匹配。 我还可以检索当前时间和项目数组时间之间的分钟差,并据此对其进行排序,但想知道是否有“更清洁”的方式。

如果有人知道任何可以简化此操作的助手,我正在使用 codeigniter。

任何帮助表示赞赏,干杯。

【问题讨论】:

    标签: php arrays codeigniter datetime


    【解决方案1】:

    我建议你使用usort:

    $time_now = new DateTime('...');
    $times=[...];
    
    function cmp($a, $b) {
        if ($a == $b) {
            return 0;
        }
        return 
           ($today->diff(new DateTime($a)) < $today->diff(new DateTime($b)))
               ? -1 : 1;
    }
    
    usort($times, "cmp");
    

    希望对你有帮助。

    【讨论】:

      【解决方案2】:

      如果您有一个字符串数组,也许您可​​以先对数组进行排序,然后尝试根据索引重新排列它......像这样?

      <?
      $times = array("23:00:00","00:30:00","19:00:00","20:30:00","00:00:00");
      $times = sortByTime($times);
      
      $nextTimes = getNextTimes($times,"14:47:57");
      var_dump($nextTimes);
      
      function sortByTime($array)
      {
              $ret = array();
              foreach($array as $time)
              {
                      $ret[strtotime($time)] = $time;
              }
              ksort($ret);
              return $ret;
      }
      
      function getNextTimes($array,$hour)
      {
              $timestamp = strtotime($hour);
              $index = 0;
              foreach($array as $key=>$val)
              {
                      if($timestamp < $key)
                      {
                              break;
                      }
                      $index++;
              }
              return array_merge(array_splice($array,$index),array_splice($array,0,$index));
      }
      ?>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-10-29
        • 1970-01-01
        • 1970-01-01
        • 2018-10-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多