我有一个返回时间列表的数组,但它的顺序如下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是时代。
有什么建议吗?
其中
一种方法是在排序时将低于"10"的时间"暂时"增加到"下一个"天))如果要处理 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,如果是,则输出它,如果不是,请将其放入缓冲区中,以便在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);
}
这只是
一个建议。如果您总是收到如下数组: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.