如何按时间顺序排列时间? [英] How to sort an array of times chronologically?

查看:415
本文介绍了如何按时间顺序排列时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非关联数组,其中输入的数据未排序(我从外部系统接收数据,无法强制其按排序顺序进入数组.)是否有任何排序方法价值?我已经尝试过了:

I have a non-associative array where the data that comes in is not sorted (I'm receiving the data from an outside system and cannot force it to come into the array in sorted order.) Is there any way to sort the values? I've tried this:

$wedTrackTimes = array("9:30 AM-10:30 AM", "8:15 AM-9:15 AM", "12:30 PM-1:30 PM", "2:00 PM-3:00 PM", "3:30 PM-4:30 PM");
$wedTrackTimes = array_unique($wedTrackTimes);
$wedTrackTimes = sort($wedTrackTimes);
print_r($wedTrackTimes);

但是它没有返回排序的数组,而是返回1.我假设这是因为它是非关联的,所以没有键.有什么方法只能按值对数组排序吗?我们确实需要9:30 AM时隙落在8:15 AM时隙之后,

But instead of returning a sorted array, it returns 1. I'm assuming it's because it's non-associative, so there are no keys. Is there any way to sort an array by value only? We really need the 9:30 AM time slot to fall after the 8:15 AM slot, as it should.

更新

感谢大家的回答;确实使数组排序,但不符合预期.如果使用默认的排序类型,则会得到以下信息:

Thanks to all for the answers; that did make the array sort, but not as expected. If I use the default sort type, I get this:

Array
(
    [0] => 12:30 PM-1:30 PM
    [1] => 2:00 PM-3:00 PM
    [2] => 3:30 PM-4:30 PM
    [3] => 8:15 AM-9:15 AM
    [4] => 9:30 AM-10:30 AM
)

使用SORT_NUMERIC,我得到了:

Using SORT_NUMERIC I get this:

Array
(
    [0] => 2:00 PM-3:00 PM
    [1] => 3:30 PM-4:30 PM
    [2] => 8:15 AM-9:15 AM
    [3] => 9:30 AM-10:30 AM
    [4] => 12:30 PM-1:30 PM
)

使用SORT_STRING我得到了:

Using SORT_STRING I get this:

Array
(
    [0] => 12:30 PM-1:30 PM
    [1] => 2:00 PM-3:00 PM
    [2] => 3:30 PM-4:30 PM
    [3] => 8:15 AM-9:15 AM
    [4] => 9:30 AM-10:30 AM
)

我需要的是:

Array
(
    [0] => 8:15 AM-9:15 AM
    [1] => 9:30 AM-10:30 AM
    [2] => 12:30 PM-1:30 PM
    [3] => 2:00 PM-3:00 PM
    [4] => 3:30 PM-4:30 PM


)

这可能吗?

推荐答案

因此,您似乎正在寻找比标准排序更高级的东西.

So, it looks like you're looking for something a little more advanced than a standard sort.

// WARNING: THIS IS *NOT* BY REFERENCE. IT RETURNS A NEW ARRAY.
function getSortedTimes(array $group)
{
    $tmp = array();
    foreach( $group as $times )
    {
        // Basically, I am pairing the string for the start time with 
        // a numeric value.
        $tmp[$times] = strtotime(substr($times, 0, strpos($times, '-')));
    }
    // asort is like sort, but it keeps the pairings just created.
    asort($tmp);
    // the keys of $tmp now refer to your original times.
    return array_keys($tmp);
}

这篇关于如何按时间顺序排列时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆