Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting by several array columns with usort [duplicate]

I am aware of the fact that I can usort an array by one column using something like this:

function cmp($a, $b)
{
    return $b['column'] - $a['column'];
}

usort($array, "cmp");

This simulates the ORDER BY column DESC.

What if I want to simulate the ORDER BY column1 DESC, column2 ASC or ORDER BY column1, column2 DESC or also by more columns? Is it possible with PHP or it's pretty much a work that just SQL can do? Thanks.

like image 382
Keaire Avatar asked Oct 21 '25 15:10

Keaire


1 Answers

I believe you mean array-multisort

array_multisort — Sort multiple or multi-dimensional arrays

Simple example:

$data[] = array('volume' => 67, 'edition' => 2);
$data[] = array('volume' => 86, 'edition' => 1);
$data[] = array('volume' => 85, 'edition' => 6);
$data[] = array('volume' => 98, 'edition' => 2);
$data[] = array('volume' => 86, 'edition' => 6);
$data[] = array('volume' => 67, 'edition' => 7);

array_multisort(array_column($data, 'volume'), SORT_DESC, array_column($data, 'edition'), SORT_ASC, $data);

This will make $data sort first by volume field in DESC and then by edition field in ASC.

like image 168
dWinder Avatar answered Oct 23 '25 05:10

dWinder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!