PHP foreach调整顺序

时间:2014-11-17 19:43:30

标签: php foreach

我有一个返回一个时间列表的数组,但它会按照这样的顺序放置01:00:00, 02:00:00, 03:00:00, 04:00:00, 05:00:00, 10:00:00, 11:00:00, 12:00:00

我希望将此顺序更改为10:00:00, 11:00:00, 12:00:00, 01:00:00, 02:00:00, 03:00:00, 04:00:00, 05:00:00

最好的方法是什么?

这是我的PHP代码:

foreach($thursday as $y => $x){
  echo '<tr>';
  foreach($x as $a => $b){
          echo '<td>' . $b . '</td>';
  }
  echo '</tr>';
}

$ b是时间。

有什么建议吗?

3 个答案:

答案 0 :(得分:2)

其中一种方式只是暂时的&#39;增加时间低于&#39; 10&#39;进入&#39; next&#39;排序的一天))如果你想处理09或08,只需修改条件。

$data = explode(', ', '01:00:00, 02:00:00, 03:00:00, 04:00:00, 05:00:00, ' .
                      '10:00:00, 11:00:00, 12:00:00');

usort($data, function($el1, $el2) {
   if ($el1[0] == '0')
       $el1 = strtotime($el1 . ' +1 day');
   else
       $el1 = strtotime($el1);

   if ($el2[0] == '0')
       $el2 = strtotime($el2 . ' +1 day');
   else
       $el2 = strtotime($el2);

   return $el1 > $el2;  
});

var_dump($data);

结果

array(8) {
  [0]=>
  string(8) "10:00:00"
  [1]=>
  string(8) "11:00:00"
  [2]=>
  string(8) "12:00:00"
  [3]=>
  string(8) "01:00:00"
  [4]=>
  string(8) "02:00:00"
  [5]=>
  string(8) "03:00:00"
  [6]=>
  string(8) "04:00:00"
  [7]=>
  string(8) "05:00:00"
}

答案 1 :(得分:0)

这是一个非常特殊的解决方案,但检查第一个字符是否等于1并输出它,如果不是,请将其放在缓冲区中以便在foreach完成后显示。

$append = '';
foreach ($x as $a => $b) {
    if (substr($b, 0, 1) === '1') {
        echo '<td>'.$b.'</td>';
    } else {
        $append .= '<td>'.$b.'</td>';
    }
}
echo $append;

从我能看到的最好的情况来看,你试图从特定的时间开始计算上升时间。这是一个功能:

function sortAscendingFromTime($array, $time = '00:00:00') {
    function cmp($a, $b) {
        if (strtotime($a) == strtotime($b)) {
            return 0;
        }
        return (strtotime($a) < strtotime($b)) ? -1 : 1;
    }
    uasort($array, 'cmp');
    $newArray = array();
    $endArray = array();
    $timestamp = strtotime($time);
    foreach ($array as $a) {
        if (strtotime($a) < $timestamp) {
            $endArray[] = $a;
        } else {
            $newArray[] = $a;
        }
    }
    return array_merge($newArray, $endArray);
}

答案 2 :(得分:0)

这只是一个建议。如果您总是收到如下数组:01:00:00, 02:00:00, 03:00:00, 04:00:00, 05:00:00, 10:00:00, 11:00:00, 12:00:00(我的意思是,按小时排序),就这种情况而言,您可以简单地制作另一个数组。

<?php
    //array with dates.
    $dates = array("01:00:00", "02:00:00", "03:00:00", "04:00:00", "05:00:00", "10:00:00",  "11:00:00", "12:00:00");
    // get the first 5 hours. 
    $newarray = array_slice($dates, 0, 5 );
    // get the last 3 hours.
    $newarray2 = array_slice($dates, 5, 8);
    // now, merge it, putting the last 3 in the start.
    $dates = array_merge($newarray2, $newarray); // and we're done.