Sort PHP arrays in detail. PHP array sorting is actually sorting the PHP array. in this article, we also sort the result set queried by the database. Sometimes the database query results cannot be directly used. in PHP array sorting, the PHP array is actually sorted. in this article, the result set queried by the database is also sorted. Sometimes the database query results cannot be directly used. for example, mysql and other results returned by an in statement must be sorted in some way. In this case, you need to sort the PHP array. For sorting database results, see the following example:
In this example, each unit in the data array represents a row in a table. This is a typical way for databases to store array data.
The data in the example is as follows:
Volume | edition
------- + --------
67 | 2
86 | 1
85 | 6
98 | 2
86 | 6
67 | 7
All data is stored in an array named data. This is usually the result obtained from the database through a loop. for example, mysql_fetch_assoc () (in fact, you can think of this function as the same as mysql_fetch_assoc () function, for specific differences, see the key differences in the PHP Manual ).
$ Data [] = array ('Volume '=> 67, 'version' => 2 );
$ Data [] = array ('Volume '=> 86, 'version' => 1 );
$ Data [] = array ('Volume '=> 85, 'version' => 6 );
$ Data [] = array ('Volume '=> 98, 'version' => 2 );
$ Data [] = array ('Volume '=> 86, 'version' => 6 );
$ Data [] = array ('Volume '=> 67, 'version' => 7 );
In this example, we will sort volume in descending order and edition in ascending order.
Now we have an array containing rows, but array_multisort () needs an array containing columns. Therefore, we use the following code to obtain and sort columns.
// Obtain the column list foreach ($ data as $ key => $ row) {$ volume [$ key] = $ row ['Volume ']; $ edition [$ key] = $ row ['version'];} // sort data by volume in descending order, sort $ data by edition in ascending order // use $ data as the last parameter and sort array_multisort ($ volume, SORT_DESC, $ edition, SORT_ASC, $ data) with a common key ); |
The data set is sorted as follows:
Volume | edition
------- + --------
98 | 2
86 | 1
86 | 6
85 | 6
67 | 2
67 | 7
In fact, there are still many ways to use in sorting, such as the arsort (), asort (), ksort (), krsort (), natsort (), natcasesort (), rsort (), usort (), array_multisort (), and uksort ().
Bytes. Sometimes the database query results cannot be used directly...