将时间字符串数组自然排序

4

我需要对一个非补零的时间字符串数组进行自然排序。

示例数据:

$totlahourdat1 = ["9:30", "15:00", "13:00"];

当我尝试使用array_multisort($totlahourdat1, SORT_DESC)时,数据似乎没有改变。
我的实际代码:
while($row11 = mysqli_fetch_array($hourget))
{
    $totlahourdat1[] = strtotime($row11['hours']); 
}   

array_multisort($totlahourdat1, SORT_DESC);

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

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

最终,数组数据应按时间从早到晚排序:

["9:30", "13:00", "15:00"]
5个回答

3

它可以工作,但它没有改变我在另一个循环中需要的关键值。 - Harpreet Singh
@Harpreet,那么你可以调用array_values()或者直接使用我的答案……显然比被采纳的答案更简单。 - mickmackusa

3
只需按照以下方式操作:
$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));

Output:-https://eval.in/835353


这个也不错,但是@squareCircle的答案需要更少的计算。 - localheinz
@localheinz 是的,但索引可能会是一个小问题:- https://eval.in/835350 (但是,这确实是最短的方法) - Alive to die - Anant
他只是将时间戳按照“降序”排序,这就是 OP 代码的问题所在。 - Accountant م

1
您可以使用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,您可以使用太空船操作符来大大减小排序函数的大小。
$times = array("9:30", "15:00", "13:00");

usort($times, function ($a, $b) {
    return strtotime($b) <=> strtotime($a);
});

0
你的问题比你想象的要简单得多。你只是忘记使用正确的顺序而已。
只需按 ASC 排序即可。
array_multisort($totlahourdat1, SORT_ASC);

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


如果你只是进行“单一排序”,为什么要调用“multisort()”函数呢? - mickmackusa
这个答案可以被证明是不正确的。https://3v4l.org/UYZlO - mickmackusa

0

您不需要使用strtotime()或日期时间方法来解析这些时间表达式,只需自然排序即可。

代码:(演示

sort($totlahourdat1, SORT_NATURAL);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接