php 在php中按日期降序按日期对数组进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16733128/
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 by date in descending order by date in php
提问by Neeraj Sharma
I have an array and I want to sort it by date. I am not able to sort it properly by date in descending order. Please help.
我有一个数组,我想按日期对其进行排序。我无法按日期按降序对其进行正确排序。请帮忙。
Array
(
[1] => Array
(
[1] => 11/05/2013
[2] => Executive Planning Day
)
[2] => Array
(
[1] => 13/06/2013
[2] => Middle Leaders Planning Day
)
[3] => Array
(
[1] => 12/07/2013
[2] => New Staff Induction Day
)
[4] => Array
(
[1] => 13/04/2013
[2] => Staff Conference Day No. 1
)
[5] => Array
(
[1] => 14/04/2013
[2] => Staff Conference Day No. 2
)
[6] => Array
(
[1] => 15/02/2013
[2] => Staff Conference Day No. 3
)
[7] => Array
(
[1] => 16/03/2013
[2] => Australia Day
)
)
回答by Gautam3164
Try like this
像这样尝试
function sortFunction( $a, $b ) {
return strtotime($a[1]) - strtotime($b[1]);
}
usort($data, "sortFunction"); //Here You can use asort($data,"sortFunction")
or you may try by detail like(its just suggestion)
或者你可以尝试像这样的细节(这只是建议)
function sortFunction($a,$b)
if ($a[1] == $b[1]) return 0;
return strtotime($a[1]) - strtotime($b[1]);
}
usort($data,"sortFunction");
As the strtotime is not obey d/m/Y formattry like this
由于strtotime 不遵守 d/m/Y 格式,请尝试这样
$orderByDate = $my2 = array();
foreach($data as $key=>$row)
{
$my2 = explode('/',$row[1]);
$my_date2 = $my2[1].'/'.$my2[0].'/'.$my2[2];
$orderByDate[$key] = strtotime($my_date2);
}
array_multisort($orderByDate, SORT_DESC, $data);
回答by jmontross
I spent a night working on how to do this for my own similar issue. To sort an associative array by date of a key in that array.
我花了一个晚上的时间研究如何为我自己的类似问题做到这一点。按该数组中键的日期对关联数组进行排序。
Both usort and uasortrequire a sort function that you must write and pass as the second parameter. The sort function is used by usort and uasort to compare each item in the array and store the result as $yourArray
usort 和uasort都需要一个排序函数,您必须编写该函数并将其作为第二个参数传递。usort 和 uasort 使用 sort 函数比较数组中的每一项,并将结果存储为 $yourArray
function sortFunction( $a, $b ) {
return strtotime($a[1]) - strtotime($b[1]);
}
uasort($yourArray, "sortFunction");
回答by Ahmad Sayeed
I jumped here for associative array sorting and found this amazing function on http://php.net/manual/en/function.sort.php. This function is very dynamic that sort in ascending and descending order with specified key.
我跳到这里进行关联数组排序,并在http://php.net/manual/en/function.sort.php上发现了这个惊人的函数。此函数非常动态,可以使用指定的键按升序和降序排序。
Simple function to sort an array by a specific key. Maintains index association.
按特定键对数组进行排序的简单函数。维护索引关联。
<?php
function array_sort($array, $on, $order=SORT_ASC)
{
$new_array = array();
$sortable_array = array();
if (count($array) > 0) {
foreach ($array as $k => $v) {
if (is_array($v)) {
foreach ($v as $k2 => $v2) {
if ($k2 == $on) {
$sortable_array[$k] = $v2;
}
}
} else {
$sortable_array[$k] = $v;
}
}
switch ($order) {
case SORT_ASC:
asort($sortable_array);
break;
case SORT_DESC:
arsort($sortable_array);
break;
}
foreach ($sortable_array as $k => $v) {
$new_array[$k] = $array[$k];
}
}
return $new_array;
}
$people = array(
12345 => array(
'id' => 12345,
'first_name' => 'Joe',
'surname' => 'Bloggs',
'age' => 23,
'sex' => 'm'
),
12346 => array(
'id' => 12346,
'first_name' => 'Adam',
'surname' => 'Smith',
'age' => 18,
'sex' => 'm'
),
12347 => array(
'id' => 12347,
'first_name' => 'Amy',
'surname' => 'Jones',
'age' => 21,
'sex' => 'f'
)
);
print_r(array_sort($people, 'age', SORT_DESC)); // Sort by oldest first
print_r(array_sort($people, 'surname', SORT_ASC)); // Sort by surname
回答by Vedran ?ego
回答by Emissary
Not entirely happy with all of the answers here so I thought I'd mention that if you wish to sort an associativearray preserving the keys then you should use uasort
rather than usort
. You can also parse the date from any format you like with the DateTime
library which also includes some predefined constantsfor some of the standard formats.
对这里的所有答案并不完全满意,所以我想我会提到,如果您希望对保留键的关联数组进行排序,那么您应该使用uasort
而不是usort
. 您还可以使用DateTime
库从您喜欢的任何格式解析日期,该库还包括一些标准格式的一些预定义常量。
uasort($array, function($a, $b){
$format = 'd/m/Y';
$ascending = false;
$zone = new DateTimeZone('UTC');
$d1 = DateTime::createFromFormat($format, $a[1], $zone)->getTimestamp();
$d2 = DateTime::createFromFormat($format, $b[1], $zone)->getTimestamp();
return $ascending ? ($d1 - $d2) : ($d2 - $d1);
});
回答by Ven
I'd build an array for ordering.
我会构建一个用于订购的数组。
$ordered = array();
foreach ($planning as $event) {
$ordered[$event['date']] = $event;
}
ksort($ordered);
回答by Vivek Sadh
Use usort(Sort an array by values using a user-defined comparison function).
使用 usort(使用用户定义的比较函数按值对数组进行排序)。
usort($array, function($a1, $a2) {
$value1 = strtotime($a1['date']);
$value2 = strtotime($a2['date']);
return $value1 - $value2;
});
回答by Sagan
so do it like this:
所以这样做:
//your array
$arr = array();
array_push($arr, array("11/05/2013", "Executive Planning Day"));
array_push($arr, array("13/06/2013", "Middle Leaders Planning Day"));
array_push($arr, array("12/07/2013", "New Staff Induction Day"));
array_push($arr, array("13/04/2013", "Staff Conference Day No. 1"));
array_push($arr, array("14/04/2013", "Staff Conference Day No. 2"));
array_push($arr, array("15/02/2013", "Staff Conference Day No. 3"));
array_push($arr, array("16/03/2013", "Australia Day"));
var_dump($arr);
function sortDateDesc($a, $b){
$strA = implode("-", array_reverse( explode("/", $a[0]) ) );
$strB = implode("-", array_reverse( explode("/", $b[0]) ) );
return strtotime($strB) - strtotime($strA);
}
usort($arr, "sortDateDesc");
var_dump($arr);
If your date format is constant day/month/year then you need to pass it in a string format recognized by the parser and year-month-day is an ISO standard if I remember it well, that one works fine
如果您的日期格式是固定的日/月/年,那么您需要以解析器识别的字符串格式传递它,如果我记得很清楚,年-月-日是 ISO 标准,那么它工作正常
回答by JokiRuiz
The solution of @Gautam3164 is almost perfect. You need to change the format of the dates. I'd say:
@Gautam3164 的解决方案几乎是完美的。您需要更改日期的格式。我会说:
function sortFunction( $a, $b ) {
return strtotime(str_replace('/', '-',$a[1])) - strtotime(str_replace('/', '-',$b[1]));
}
usort($data, "sortFunction"); //Here You can use asort($data,"sortFunction")
11/10/1987 -> 10 Nov 1987 11-10-1987 -> 11 Oct 1987
11/10/1987 -> 1987 年 11 月 10 日 11-10-1987 -> 1987 年 10 月 11 日
回答by Masud Ahmed
$sortdate = array(
'17/08/2015',
'02/01/2017',
'05/02/2014'
);
function sortFunction($a, $b)
{
$datea = strtotime(str_replace('/', '-', $a));
$dateb = strtotime(str_replace('/', '-', $b));
if ($datea == $dateb)
{
return 0;
}
return ($datea < $dateb) ? -1 : 1;
}
usort($sortdate, "sortFunction");
echo "<pre>";
var_dump($sortdate);