3

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.

Keaire
  • 879
  • 1
  • 11
  • 30

3 Answers3

3

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.

dWinder
  • 11,597
  • 3
  • 24
  • 39
  • While it will sort by multiple columns it will not sort with usort. So if you have one column where you not just need a compare function you will have to use usort. And the question was "...with usort" :) – iRaS May 21 '19 at 04:43
  • Literally you right and you solution will work fine also. But I think this is what the OP actually wanted even if he didn't know it... – dWinder May 21 '19 at 05:13
1

It's easy. Sorting by multiple columns means that you just use another sort criterium if the first sort criterium is equal:

function cmp($a, $b)
{
  if ($a['col1'] !== $b['col1']) {
    return $b['col1'] - $a['col1'];
  }
  return $a['col2'] - $b['col2'];
}

usort($array, 'cmp');

this is the same like ORDER BY col1 DESC, col2 ASC

While it seems some bit more code than the multisort it is much more flexible. Depends if you want to calculate something inside. For example: sort by the length of a column.

iRaS
  • 1,958
  • 1
  • 16
  • 29
0

You can do using foreach loop, $data sorting.

<?php
   $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);

// Obtain a list of columns
foreach ($data as $key => $row) {
    $volume[$key]  = $row['volume'];
    $edition[$key] = $row['edition'];
}

// Sort the data with volume descending, edition ascending
// Add $data as the last parameter, to sort by the common key
array_multisort($volume, SORT_DESC, $edition, SORT_ASC, $data);
var_dump($data);

Working DEMO

Ghanshyam Nakiya
  • 1,602
  • 17
  • 24