Reputation: 9034
Maybe what I want is 'too' custom and has to be done manually, I thought usort
can do it but seems I don't understand it completely. Sorting an array of shows by date in descending order but if date is current year then put those in the beginning of the array:
usort($show, function($a, $b){
$year = (int) date("Y", time());
$a = $a['date'];
$b = $b['date'];
if ($a === $year) return -1;
if ($b === $year) return -1;
if ($a === $b) return 0;
return ($a > $b) ? -1 : 1;
});
Upvotes: 0
Views: 62
Reputation: 43451
If $a
is current year and $b
is not current year, put $a
first.
If $a
is not current year and $b
is current year, put $b
first.
Otherwise just do simple comparison/sorting for $a
and $b
:
$array = array(
1890,
1725,
2000,
2004,
2015,
2016,
2050,
2156,
2019,
);
usort($array, function ($a, $b) {
$y= date('Y');
if ($a == $y && $b != $y) {
return -1;
} elseif ($a != $y && $b == $y) {
return 1;
}
return $b - $a;
});
var_dump($array);
// output
Array
(
[0] => 2015
[1] => 2156
[2] => 2050
[3] => 2019
[4] => 2016
[5] => 2004
[6] => 2000
[7] => 1890
[8] => 1725
)
Upvotes: 1