PHP - Multiple uasort functions breaks sorting

前端 未结 3 1362
悲哀的现实
悲哀的现实 2020-12-01 22:18

I have a multidimensional array that stores people.

Array (
   id93294 => (array (
             Name => \"Tom Anderson\",
             Birthday => \         


        
3条回答
  •  半阙折子戏
    2020-12-01 22:56

    Many years later, there is a cleaner, more succinct technique provided from PHP7+ ...the spaceship operator and balanced arrays of "criteria".

    Code: (Demo)

    uasort($array, function($a, $b) {
        return [strtotime($a['Birthday']), $a['Hometown'] !== $a['CurrentLocation'], $a['Name']]
               <=>
               [strtotime($b['Birthday']), $b['Hometown'] !== $b['CurrentLocation'], $b['Name']];
    });
    var_export($array);
    

    See the demo link for sample input and the output.

    This snippet will sort by:

    1. Birthday ASC then
    2. Hometown === CurrentLocation before not === then
    3. Name ASC

    Note: #2 has !== syntax only because false evaluation are treated as 0 and true evaluations are treated as 1.

    If you need to change any of the sorting orders for any of the criteria, just swap the $a and $b at the corresponding elements.

提交回复
热议问题