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.
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.