For this example, each element in the data
array represents one row in a table. This type of dataset is typical
of database records.
volume | edition
-------+--------
67 | 2
86 | 1
85 | 6
98 | 2
86 | 6
67 | 7
The data as an array, called data. This would usually,
for example, be obtained by looping with mysqli_fetch_assoc().
In this example, we will order by volume descending,
edition ascending.
We have an array of rows, but array_multisort()
requires an array of columns, so we use the below code to obtain the
columns, then perform the sorting.
<?php
// The data as created by looping over mysqli_fetch_assoc:
$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'];
}
// You can use array_column() instead of the above code
$volume = array_column($data, 'volume');
$edition = array_column($data, '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);
// Loop over the data and output the sorted values for each column
echo 'volume | edition', PHP_EOL;
echo '-------+--------', PHP_EOL;
for ($i = 0; $i < count($data); $i++) {
printf("%6d | %7d\n", $volume[$i], $edition[$i]);
}
?>
The dataset is now sorted, and will look like this:
volume | edition
-------+--------
98 | 2
86 | 1
86 | 6
85 | 6
67 | 2
67 | 7