Sorting by Multiple Array Columns in PHP

Lets say you want to place resultsets from multiple queries into an array in php and sort this single massive array within php. This is very possible. You can even sort on multiple columns with different sort order by alpha or numeric for each column. This method is ideal rather then trying to make one huge mess of a query from large data tables with many joins that will tax your db server. You use the array_multisort() to meet all your sorting needs.

Here is the dataset we will be using.

$data[] = Array('publication'=>'dpmag','volume'=>3);
$data[] = Array('publication'=>'hdmag','volume'=>3);
$data[] = Array('publication'=>'dpmag','volume'=>8);
$data[] = Array('publication'=>'opmag','volume'=>3);
$data[] = Array('publication'=>'dpmag','volume'=>10);
$data[] = Array('publication'=>'opmag','volume'=>7);
$data[] = Array('publication'=>'hdmag','volume'=>6);
$data[] = Array('publication'=>'opmag','volume'=>1);
$data[] = Array('publication'=>'hdmag','volume'=>8);

You first extract out the column keys you want to sort. Will first sort by magazine publication name in ascending order and then by volume number in descending order. The extracted column variable names need to be same as hash index names.

foreach ($data as $key => $row) {
    $volume[$key]  = $row['volume'];
    $publication[$key] = $row['publication'];

With the use of the column keys you can now sort entire array by these columns and keep the row index value intact if they are non-numeric. This is good if your using some kind of hashed index.

array_multisort($publication, SORT_ASC, $volume, SORT_DESC, $data);

print_r($data); //array dump. You will see that $data was resorted 
in the correct manner.

Leave a comment