I\'m trying to do the same as MySQL query
SELECT * FROM table ORDER BY field1, field2, ...
but with php and a multidimensional array:
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.