Skip to content

Instantly share code, notes, and snippets.

@bruceh48
Created February 19, 2017 04:33
Show Gist options
  • Save bruceh48/b7bb7fe309570e1c2f019a275ed94277 to your computer and use it in GitHub Desktop.
Save bruceh48/b7bb7fe309570e1c2f019a275ed94277 to your computer and use it in GitHub Desktop.
Sort an array of arrays in PHP
<?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