How do I use the php array_multisort function to sort database results in a complex way

  • 2020-06-12 08:37:34
  • OfStack

First, let's talk about the requirements: there are four fields in the database, namely id,volume,edition and name. It is required to sort the query results according to volume+edition from large to small.
The array_multisort function is next
array_multisort() can be used to sort multiple arrays once, or to sort multi-dimensional arrays based on one or more dimensions.

The associated (string) key name remains the same, but the numeric key name is re-indexed.

Sorting order flag:
The SORT_ASC wok is sorted in ascending order
The SORT_DESC trick is sorted in descending order

Sort type flag:
The SORT_REGULAR wok compares items in the usual way
The SORT_NUMERIC wc3 compares items by value
The SORT_STRING wm_compares items as strings

Two sort flags of the same kind cannot be specified after each array. The sort flags specified after each array are valid only for that array. The default values before that are SORT_ASC and SORT_REGULAR.

The input array is treated as columns of a table and sorted by rows -- similar to the ORDER BY clause of SQL. The first array is the primary array to sort. If the rows (values) in the array are the same, sort them by the size of the corresponding values in the next input array, and so on.

The parameter structure of this function is somewhat unusual, but very flexible. The first argument must be an array. Each of the next arguments can be an array or the sort flags listed below.

So now we have this set of data


//  This is a 1 Group the results of a query from a database 
$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);
// We need to do that first 1 a volume+edition The array to 
foreach($data as $val){
     $arr[] = $val['volume'] + $val['edition']; 
}
//  will $arr In descending order 
//  the  $data  As a final 1 Parameters, sorted by generic key 
array_multisort($arr, SORT_DESC, $data);

That's what we need


Related articles: