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

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

问题描述

我有一个这种格式的数组:

I have an array in this format:

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'
]

也许当它采用这种格式时,我可以遍历它们,删除所有 '-'(连字符)标记,使它们保留为整数,使用 array_sort() 并再次遍历它们以对它们进行排序?如果有另一种方式,我会更喜欢,因为我会对每个用户进行 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.

谢谢.

我也可以这样做:

$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) 格式而不是english"格式,然后只需使用 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.

编辑 我看到您现在更正了您的问题,以表明您实际上有一个数组数组,并且排序键位于子数组中.在这种情况下,您应该按照其他地方的建议使用 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天全站免登陆