php PHP按日期排序数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6401714/
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
PHP order array by date?
提问by Jens T?rnell
Possible Duplicate:
PHP Sort a multidimensional array by element containing date
可能的重复:
PHP 按包含日期的元素对多维数组进行排序
I have some data from XML or JSON in a PHP array that looks like this:
我在 PHP 数组中有一些来自 XML 或 JSON 的数据,如下所示:
[0]= array(2) {
["title"]= string(38) "Another title"
["date"]= string(31) "Fri, 17 Jun 2011 08:55:57 +0200"
}
[1]= array(2) {
["title"]= string(38) "My title"
["date"]= string(31) "Mon, 16 Jun 2010 06:55:57 +0200"
}
What I want to do is order the two items by date.
我想要做的是按日期订购这两个项目。
- Is it possible to sort by date, when the sort value is inside every item?
- Do I need to convert the date format to timestamp?
- 当排序值在每个项目中时,是否可以按日期排序?
- 我需要将日期格式转换为时间戳吗?
What I don't want to do
我不想做的事
I could use date and set it as the ID but that don't feel right, because two items can have the same date and then it would not be unique.
我可以使用 date 并将其设置为 ID,但这感觉不对,因为两个项目可以具有相同的日期,然后它就不会是唯一的。
回答by KARASZI István
You don't need to convert your dates to timestamp before the sorting, but it's a good idea though because it will take more time to sort without it.
您不需要在排序之前将日期转换为时间戳,但这是一个好主意,因为没有它需要更多时间进行排序。
$data = array(
array(
"title" => "Another title",
"date" => "Fri, 17 Jun 2011 08:55:57 +0200"
),
array(
"title" => "My title",
"date" => "Mon, 16 Jun 2010 06:55:57 +0200"
)
);
function sortFunction( $a, $b ) {
return strtotime($a["date"]) - strtotime($b["date"]);
}
usort($data, "sortFunction");
var_dump($data);
回答by phihag
回答by Ond?ej Mirtes
I recommend using DateTime objects instead of strings, because you cannot easily compare strings, which is required for sorting. You also get additional advantages for working with dates.
我建议使用 DateTime 对象而不是字符串,因为您无法轻松比较排序所需的字符串。您还可以获得处理日期的额外优势。
Once you have the DateTime objects, sorting is quite easy:
一旦你有了 DateTime 对象,排序就很容易了:
usort($array, function($a, $b) {
return ($a['date'] < $b['date']) ? -1 : 1;
});
回答by Melsi
He was considering having the date as a key, but worried that values will be written one above other, all I wanted to show (maybe not that obvious, that why I do edit) is that he can still have values intact, not written one above other, isn't this okay?!
他正在考虑将日期作为关键,但担心值会被写在另一个之上,我想表明的(也许不是那么明显,这就是我为什么要编辑)是他仍然可以保留完整的值,而不是写一个高于其他,这不好吗?!
<?php
$data['may_1_2002']=
Array(
'title_id_32'=>'Good morning',
'title_id_21'=>'Blue sky',
'title_id_3'=>'Summer',
'date'=>'1 May 2002'
);
$data['may_2_2002']=
Array(
'title_id_34'=>'Leaves',
'title_id_20'=>'Old times',
'date'=>'2 May 2002 '
);
echo '<pre>';
print_r($data);
?>