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.