PHP按包含日期的元素排序多维数组 [英] PHP Sort a multidimensional array by element containing date
问题描述
我有一个数组,例如:
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
)
)
任何人都可以建议一种基于datetime元素排序/排序的方法?
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
然后将每个记录的datetime
字段提取为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屋!