0

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;
    });
1
  • It does not work like this way. usort (like any other user-defined comparison functions) does not declare strict order in which elements will be compared. Solution may be - two steps of sorting, first: sort elements by date (sort by "year"), second: put current year elements to the beginning (sort by "year == current year") Commented Oct 12, 2015 at 7:40

1 Answer 1

1

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
)

LIVE

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.