按日期键按子数组排序PHP数组
问题描述:
I know this question has been asked a hundred times, and I've gone through multiple answers and am not getting the correct results.
I am trying to order the following row by date, oldest first:
Array(
[0] => Array
(
[0] => '3173'
[1] => 'Contact - 12-6-14 Outstanding invoice'
[2] => '16/06/2014'
[3] => '204'
)
[1] => Array
(
[0] => '3167'
[1] => 'Contact - Outstanding invoice'
[2] => '13/06/2014'
[3] => '207'
)
[2] => Array
(
[0] => '3497'
[1] => 'New Site - Keri Keri'
[2] => '25/11/2014'
[3] => '43'
)
[3] => Array
(
[0] => '2023'
[1] => 'Analysis'
[2] => '17/06/2014'
[3] => '355'
)
[4] => Array
(
[0] => '2641'
[1] => 'PSS'
[2] => '20/02/2014'
[3] => '321'
)
)
I have tried things such as the below with no luck.
function cmp($a, $b){
return $b[2] - $a[2];
}
usort($urgent_array, "cmp");
Any help on this one would be really appreciated :)
答
First, you want to compare, not subtract:
function cmp($a, $b) {
if ($a[2] == $b[2])
return 0;
return ($a[2] > $b[2]) ? 1 : -1;
}
usort($urgent_array, "cmp");
Then, date ordering works best if you use the Y-m-d
format:
2014-06-13
etc.
答
Change your compare function to
function cmp($a, $b){
$a_date = strtotime(str_replace('/', '-', $a[2]));
$b_date = strtotime(str_replace('/', '-', $b[2]));
return $a_date - $b_date;
}
You want to use strtotime because subtracting strings doesn't really mean anything. The str_replace is because PHP expects dashes for dd-mm-yyyy format.