PHP排序多维数组由包含元素日期 [英] PHP Sort a multidimensional array by element containing date

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

问题描述

我有一个数组,如:

Array
(
[0] => Array
    (
        [id] => 2
        [type] => comment
        [text] => hey
        [datetime] => 2010-05-15 11:29:45
    )

[1] => Array
    (
        [id] => 3
        [type] => status
        [text] => oi
        [datetime] => 2010-05-26 15:59:53
    )

[2] => Array
    (
        [id] => 4
        [type] => status
        [text] => yeww
        [datetime] => 2010-05-26 16:04:24
    )

)

任何人都可以提出一个方法排序/订购此基础日期时间元素?

Can anyone suggest a way to sort/order this based on the datetime element?

推荐答案

使用 usort() 和一个自定义比较函数:

Use usort() and a custom comparison function:

function date_compare($a, $b)
{
    $t1 = strtotime($a['datetime']);
    $t2 = strtotime($b['datetime']);
    return $t1 - $t2;
}    
usort($array, 'date_compare');


修改:您的数据在数组的数组主办。为了更好地辨别这些,让我们称之为内阵列(数据)记录,让您的数据确实是一组记录。


EDIT: Your data is organized in an array of arrays. To better distinguish those, let's call the inner arrays (data) records, so that your data really is an array of records.

usort 将通过两种这些记录给定的比较函数 date_compare()在一个时间。 date_compare 然后提取每一条记录作为UNIX时间戳(整数)的日期时间字段,并返回的区别,这样的结果将是 0 如果这两个日期都是平等的,一个正数,如果第一个( $ A )大于或负值如果第二个参数( $ b )较大。 usort()使用该信息来对数组进行排序。

usort will pass two of these records to the given comparison function date_compare() at a a time. date_compare then extracts the "datetime" field of each record as a UNIX timestamp (an integer), and returns the difference, so that the result will be 0 if both dates are equal, a positive number if the first one ($a) is larger or a negative value if the second argument ($b) is larger. usort() uses this information to sort the array.

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

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