如何在 PHP 中对 2D 数组进行排序。 我想按日期排序,数组是这种格式:
[result] => Array
(
[0] => Array
(
[link] => http://local/node/0
[date] => 13158505310
)
[1] => Array
(
[link] => http://local/node/1
[date] => 13158505311
)
[2] => Array
(
[link] => http://local/node/2
[date] => 13158505312
使用usort:
usort( $array, function( $a, $b ){ return $a["date"] - $b["date"]; } );
用这个
function sortByDateDesc($a, $b) {
return strcmp($a["date"], $b["date"]);
}
function sortByDateAsc($a, $b) {
if ($a['date'] == $b['date']) {
return 0;
}
return ($a['date'] > $b['date']) ? -1 : 1;
}
usort($array, 'sortByDateDesc'); //Descending order
//usort($array, 'sortByDateAsc'); //Asceding order
这段代码可能对您有帮助......
// Obtain a list of columns
foreach (data as key => row) {
links[key] = row['link'];
dates[key] = row['date'];
}
// Sort the data with link descending, date ascending
// Add $data as the last parameter, to sort by the common key
array_multisort(link, SORT_DESC, date, SORT_ASC, data);