【问题标题】:Sorting time array giving wrong values in PHP排序时间数组在PHP中给出错误的值
【发布时间】:2017-12-26 12:53:59
【问题描述】:

我有一个这样的 php 数组:-

array(3) {
     [0]=>
      string(4) "9:30"
     [1]=>
      string(5) "15:00"
     [2]=>
      string(5) "13:00"
}

这次排序后,我得到了错误的数据。我正在按array_multisort 函数对其进行排序。

这是我在时间排序后得到的

array(3) {
   [0]=>
     string(5) "03:00"
   [1]=>
     string(5) "01:00"
   [2]=>
     string(5) "09:30"
 }

这是我的代码

首先我通过使用 strtotime 函数将我的时间转换为 unix 时间,然后像这样排序:

while($row11 = mysqli_fetch_array($hourget))
  {
      $totlahourdat1[] = strtotime($row11['hours']); 
      $totlahourdat2[] = $row11['hours']; 
  } 

  echo "<pre>";
    var_dump($totlahourdat2);
  echo "</pre>";
 //sort data      
 array_multisort($totlahourdat1, SORT_DESC);

 //var_dump($totlahourdat);

 foreach($totlahourdat1 as $time){
    $totlahourdat[] = date("h:i",$time);
 }

 echo "<pre>";
  var_dump($totlahourdat);
echo "</pre>";

如果我打印我的 $totlahourdat1 数组,那么我会得到这个:

array(3) {
   [0]=>
    int(1500535800)
   [1]=>
    int(1500555600)
   [2]=>
    int(1500548400)
 }

我的结果应该是这样的:

array(3) {
  [0]=>
    string(4) "9:30"
  [1]=>
    string(5) "13:00"
  [2]=>
    string(5) "15:00"
}

我们将不胜感激。

【问题讨论】:

    标签: php arrays sorting datetime time


    【解决方案1】:

    只需执行以下操作:-

    $time = array(0=>"9:30",1=>"15:00",2=>"13:00");
    function timecompare($a,$b)
    {
        return strtotime($a) < strtotime($b) ? -1: 1;
    }
    uasort($time ,'timecompare');
    
    print_r(array_values($time));
    

    输出:-https://eval.in/835353

    【讨论】:

    • 这也不错,不过@squareCircle 的回答需要较少的计算。
    • @localheinz 是的,但索引可能是一个小问题:- eval.in/835350(但是是的,这确实是最短的方法)
    • 他只对时间戳DESC进行排序,这是OP代码的问题。
    【解决方案2】:

    使用natsort($array)see function definition

    【讨论】:

    • 它可以工作,但它不会改变我在另一个循环中需要的键值
    【解决方案3】:

    您的问题比您想象的要简单得多。你只是忘了使用正确的顺序

    只需通过ASC订购

    array_multisort($totlahourdat1, SORT_ASC);
    

    在此处查看演示 (https://eval.in/835356)

    【讨论】:

      【解决方案4】:

      您可以使用usort()编写自定义排序函数。

      $times = array("9:30", "15:00", "13:00");
      
      usort($times, function ($a, $b) {
          $a = strtotime($a);
          $b = strtotime($b);
          if ($a == $b) {
              return 0;
          }
          return ($a < $b) ? 1 : -1;
      });
      

      如果你使用的是PHP7,你可以使用spaceship operator来大大减少排序函数的大小。

      $times = array("9:30", "15:00", "13:00");
      
      usort($times, function ($a, $b) {
          return strtotime($b) <=> strtotime($a);
      });
      

      【讨论】:

        猜你喜欢
        • 2014-02-13
        • 2021-08-02
        • 1970-01-01
        • 2022-06-11
        • 1970-01-01
        • 2013-07-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多