PHP排序($数组)不工作 - 返回1,而不是排序后的数组中 [英] php sort($array) not working - returning 1 instead of sorted array

查看:181
本文介绍了PHP排序($数组)不工作 - 返回1,而不是排序后的数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非关联数组,其中附带中没有排序(我从外部系统接收数据并不能强迫它来为按排序顺序排列)中的数据有什么办法来排序价值?我试过这样:

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时段的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);
}

这篇关于PHP排序($数组)不工作 - 返回1,而不是排序后的数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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