Reputation: 6292
How can I sort a 2D array in PHP. I want to sort on date, Array is in this format :
[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
Upvotes: 0
Views: 183
Reputation: 11
may be this code helpful to you....
// 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);
Upvotes: 0
Reputation: 10074
Use this
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
Upvotes: 1
Reputation: 48813
Use usort:
usort( $array, function( $a, $b ){ return $a["date"] - $b["date"]; } );
Upvotes: 3
Reputation: 373
You could also try multisort http://www.php.net/manual/en/function.array-multisort.php
Upvotes: 0