如何排序在PHP中的日期数组 [英] How to sort a date array in PHP

查看:156
本文介绍了如何排序在PHP中的日期数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这个格式的数组:

Array
(
    [0] => Array
        (
            [28th February, 2009] => 'bla'
        )

    [1] => Array
        (
            [19th March, 2009] => 'bla'
        )

    [2] => Array
        (
            [5th April, 2009] => 'bla'
        )

    [3] => Array
        (
            [19th April, 2009] => 'bla'
        )

    [4] => Array
        (
            [2nd May, 2009] => 'bla'
        )

)

我想他们在日期(根据月,日和年)的升序排列出来。什么是做到这一点的最好办法?

I want to sort them out in the ascending order of the dates (based on the month, day, and year). What's the best way to do that?

最初的电子邮件正在在MySQL日期格式牵强,因此它可以让我得到在这种状态下的数组:

Originally the emails are being fetched in the MySQL date format, so its possible for me to get the array in this state:

Array
[
    ['2008-02-28']='some text',
    ['2008-03-06']='some text'
]

或许,当它在这种格式,我可以通过他们循环,删除所有 - (连字符)标记,使他们留作integars,用它们排序 array_sort()和循环通过他们再次对他们进行排序?将preFER如果有另一种方式,因为我会做3圈这个每个用户。

Perhaps when its in this format, I can loop through them, remove all the '-' (hyphen) marks so they are left as integars, sort them using array_sort() and loop through them yet again to sort them? Would prefer if there was another way as I'd be doing 3 loops with this per user.

感谢。

编辑:我也可以这样做:

I could also do this:

$array[$index]=array('human'=>'28 Feb, 2009',
                   'db'=>'20080228',
                   'description'=>'Some text here');

不过用这个,会不会有什么方法可以基于DB单独元素?

But using this, would there be any way to sort the array based on the 'db' element alone?

编辑2:更新初始的var_dump

Edit 2: Updated initial var_dump

推荐答案

使用的ISO( YYYY-MM-DD )格式,而不是英语的格式,然后只需使用 ksort 功能让他们在正确的顺序。

Use the ISO (yyyy-mm-dd) format rather than the "english" format, and then just use the ksort function to get them in the right order.

有没有需要删除的连字符, ksort 会做的字符串键字母数字的比较,以及 YYYY-MM-DD 格式完美的作品以及词法顺序是一样的实际日期顺序。

There's no need to remove the hyphens, ksort will do an alphanumeric comparison on the string keys, and the yyyy-mm-dd format works perfectly well as the lexical order is the same as the actual date order.

修改我现在看到你们已经纠正你的问题,表明你实际上得到一个数组的数组,并且sort关键是在子阵列。在这种情况下,你应该使用 uksort 其他地方推荐的,但我会建议你去用自己的编辑和排序基于DB格式化的日期,而不是​​通过解析人类可读的格式为:

EDIT I see you've now corrected your question to show that you've actually got an array of arrays, and that the sort key is in the sub-arrays. In this case, you should use uksort as recommended elsewhere, but I would recommend that you go with your own edit and sort based on the DB formatted date, rather than by parsing the human readable format:

function cmp($a, $b)
{
    global $array;
    return strcmp($array[$a]['db'], $array[$b]['db']);
}

uksort($array, 'cmp');

这篇关于如何排序在PHP中的日期数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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