php 按日期字段对对象数组进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7127764/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sort array of objects by date field
提问by Nadine
How can I re-arrange a array of objects like this:
如何重新排列这样的对象数组:
[495] => stdClass Object
(
[date] => 2009-10-31 18:24:09
...
)
[582] => stdClass Object
(
[date] => 2010-2-11 12:01:42
...
)
...
by the date
key, oldest first ?
通过date
关键,最古老的第一?
回答by Arnaud Le Blanc
usort($array, function($a, $b) {
return strtotime($a['date']) - strtotime($b['date']);
});
Or if you don't have PHP 5.3:
或者,如果您没有 PHP 5.3:
function cb($a, $b) {
return strtotime($a['date']) - strtotime($b['date']);
}
usort($array, 'cb');
回答by MythThrazz
Since the original question is about sorting arrays of stdClass() objects, here's the code which would work if $a and $b are objects:
由于最初的问题是关于对 stdClass() 对象的数组进行排序,如果 $a 和 $b 是对象,这里的代码将起作用:
usort($array, function($a, $b) {
return strtotime($a->date) - strtotime($b->date);
});
Or if you don't have PHP 5.3:
或者,如果您没有 PHP 5.3:
function cb($a, $b) {
return strtotime($a->date) - strtotime($b->date);
}
usort($array, 'cb');
回答by Michael Irigoyen
I wanted to expand on arnaud576875
's answer. I ran across this same issue, but with using DateTimeobjects. This is how I was able to accomplish the same thing.
我想扩展arnaud576875
的答案。我遇到了同样的问题,但使用了DateTime对象。这就是我如何能够完成同样的事情。
usort($array, function($a, $b) {
return $a['date']->format('U') - $b['date']->format('U');
});
回答by Naqued
I wanted to expand on arnaud576875 and Michael Irigoyen.
我想扩展 arnaud576875 和 Michael Irigoyen。
Same issue with object containing dateTime with Symphony.
与 Symphony 包含 dateTime 的对象存在相同的问题。
I coudn't use $a['date'] because it was not an key array.
我不能使用 $a['date'] 因为它不是一个键数组。
usort($verifications, function($a, $b) {
return $a->getDate()->format('U') - $b->getDate()->format('U');
});
This solved my problem
这解决了我的问题