Created
February 19, 2017 04:33
-
-
Save bruceh48/b7bb7fe309570e1c2f019a275ed94277 to your computer and use it in GitHub Desktop.
Sort an array of arrays in PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$r = array( | |
array('year'=>2017,'month'=>1,'day'=>15), | |
array('year'=>2017,'month'=>2,'day'=>16), | |
array('year'=>2017,'month'=>2,'day'=>15), | |
array('year'=>2017,'month'=>2,'day'=>14), | |
array('year'=>2017,'month'=>3,'day'=>15), | |
array('year'=>2017,'month'=>4,'day'=>15), | |
array('year'=>2016,'month'=>5,'day'=>15), | |
array('year'=>2015,'month'=>6,'day'=>15), | |
array('year'=>2016,'month'=>7,'day'=>15), | |
array('year'=>2014,'month'=>8,'day'=>15), | |
); | |
// Want result in descending year order, and then sorted by ascending month & day order. | |
usort($r, function($a, $b) { | |
// First sort by year descending, swap "A" & "B" is you want asc. | |
$rdiff = $b['year'] - $a['year']; | |
if ($rdiff) return $rdiff; | |
// then sort by month ascending, swap "A" & "B" is you want desc. | |
$rdiff = $a['month'] - $b['month']; | |
if ($rdiff) return $rdiff; | |
// then sort by day ascending, swap "A" & "B" is you want desc. | |
$rdiff = $a['day'] - $b['day']; | |
return $rdiff; | |
}); | |
echo '<pre>';print_r($r);echo '</pre>'; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment