排序与ASORT日期(阵列)无法正常工作 [英] Sorting array with dates with asort() does not work properly

查看:147
本文介绍了排序与ASORT日期(阵列)无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是排序的数组,格式为DD-MM-YYYY:

 阵列(6){
[7-0] =>串(10)28-04-2014
[7-1] =>串(10)29-04-2014
[7-2] =>串(10)30-04-2014
[7-3] =>串(10)2014年1月5日
[7-5] =>串(10)26-04-2014
[7-6] =>串(10)27-04-2014
}

我现在使用排序:

 阵列(6){
[7-3] =>串(10)2014年1月5日
[7-5] =>串(10)26-04-2014
[7-6] =>串(10)27-04-2014
[7-0] =>串(10)28-04-2014
[7-1] =>串(10)29-04-2014
[7-2] =>串(10)30-04-2014
}

通过使用ASORT()由价值排序的数组,但ofcouse 01,现在是第一位的。有没有办法为我解决这个简单的方法?这应该是最后一个数组中,因此,在接下来的一个月了。 (2014年1月5日)

更新:

以上是ASORT前后的var_dump()响应()。下面是code片段。不同的尝试后,ASORT()一直很好,直到这个星期在那里其对月底 - 然后数组不能正确排序

  $ openhours_select =阵列();
的foreach($ openhours为$哦)
{
        $ D =日期(D-M-Y',的strtotime('本'$天[$哦['fromDay']));        $ openhours_select [$哦['身份证'] = $ D组;}ASORT($ openhours_select);


解决方案

这些日期都没有在整理一个良好的格式。你应该存储在ISO-8601格式的日期这是很容易进行排序,然后在需要时重新格式化。

但要解决这个你可以使用的DateTime :: createFromFormat()来的日期读入一个比较的格式,然后对其进行排序。

  uasort($ openhours_select,函数($ A,$ B){
    $ DATE1 =日期时间:: createFromFormat(D-M-Y',$ A);
    $ DATE2 =日期时间:: createFromFormat(D-M-Y',$ B);
    返回$ DATE1> $ DATE2;
});

This is the unsorted array, in the format dd-mm-yyyy:

array(6) { 
["7-0"]=> string(10) "28-04-2014" 
["7-1"]=> string(10) "29-04-2014"
["7-2"]=> string(10) "30-04-2014" 
["7-3"]=> string(10) "01-05-2014" 
["7-5"]=> string(10) "26-04-2014" 
["7-6"]=> string(10) "27-04-2014" 
}

I am now using sorting:

array(6) { 
["7-3"]=> string(10) "01-05-2014" 
["7-5"]=> string(10) "26-04-2014" 
["7-6"]=> string(10) "27-04-2014" 
["7-0"]=> string(10) "28-04-2014" 
["7-1"]=> string(10) "29-04-2014"
["7-2"]=> string(10) "30-04-2014" 
}

By using asort() to sort the array by the value, but ofcouse the 01 now comes first up. Is there any way for me to solve this easy way? It should be last in the array, hence its in the next month. (01-05-2014)

Update:

Above was the var_dump() response before and after the asort(). Below is the code snippet. After different attempts, asort() has worked fine until this week where its about the end of the month - then the array does not get sorted correctly.

$openhours_select = array();
foreach($openhours as $oh)
{
        $d = date('d-m-Y', strtotime('this ' . $days[$oh['fromDay']]));

        $openhours_select[$oh['id']] =$d;

}

asort($openhours_select);

解决方案

Those dates are not in a good format for sorting. You should store dates in ISO-8601 format which are easy to sort and then reformat when needed.

But to work around this you can use DateTime::createFromFormat() to read in the date into a comparable format and then sort them.

uasort($openhours_select, function($a, $b) {
    $date1 = DateTime::createFromFormat('d-m-Y', $a);
    $date2 = DateTime::createFromFormat('d-m-Y', $b);
    return $date1 > $date2;
});

这篇关于排序与ASORT日期(阵列)无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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