简体   繁体   中英

Sorting an array using PHP's usort method

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;
    });

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM