How to sort a multidimensional array by multiple columns?

前端 未结 4 1284
礼貌的吻别
礼貌的吻别 2020-12-04 01:22

I\'m trying to do the same as MySQL query

SELECT * FROM table ORDER BY field1, field2, ...

but with php and a multidimensional array:

         


        
4条回答
  •  余生分开走
    2020-12-04 01:55

    PHP7.4's arrow syntax eliminates much of the code bloat which was previously necessary to bring your column orders into the usort() scope.

    Code: (Demo)

    $orderBy = ['a', 'n'];
    usort($Test, fn($a, $b) =>
        array_map(fn($v) => $a[$v], $orderBy)
        <=>
        array_map(fn($v) => $b[$v], $orderBy)
    );
    var_export($Test);
    

    I reckon this is a very elegant and concise way to script the task. You generate the nominated column values from $a and $b as separate arrays and write the spaceship operator between them.

    Without the arrow syntax, the snippet gets a little more chunky.

    Code: (Demo)

    $orderBy = ['a', 'n'];
    usort($Test, function($a, $b) use ($orderBy) {
        return 
            array_map(function($v) use ($a){
                return $a[$v];
            }, $orderBy)
            <=>
            array_map(function($v) use ($b){
                return $b[$v];
            }, $orderBy);
    });
    var_export($Test);
    

    The spaceship operator will walk through corresponding pairs of data ([0] vs [0], then [1] vs [1], and so on) until it reaches a non-zero evaluation or until it exhausts the comparison arrays.

提交回复
热议问题