PHP multi-dimensional array sorting implementation code

Source: Internet
Author: User
Tags sorted by name

Array_multisort
(PHP 4, PHP 5)
Array_multisort -- sorts multiple arrays or multi-dimensional arrays.
Description
Bool array_multisort (array ar1 [, mixed arg [, mixed... [, array...])

If the call succeeds, TRUE is returned. If the call fails, FALSE is returned.
Array_multisort () can be used to sort multiple arrays at a time, or to sort multi-dimensional arrays based on one or more dimensions.
The Association (string) key name remains unchanged, but the number key name is re-indexed.
The input array is treated as a table column and sorted BY rows-similar to the SQL ORDER BY clause. The first array is the main array to be sorted. If the rows (values) in the array are the same, they are sorted by the corresponding values in the next input array.
The parameter structure of this function is somewhat unusual, but flexible. The first parameter must be an array. Each of the following parameters can be an array or a sorting marker listed below.
Sort order mark:

SORT_ASC-sort by Ascending Order
SORT_DESC-sort by descent

Sorting type flag:

SORT_REGULAR-compare projects by common methods
SORT_NUMERIC-compare projects by numerical values
SORT_STRING-compare items by string

You cannot specify two sorting flags of the same type after each array. The sorting flag specified after each array is only valid for this array-the default values are SORT_ASC and SORT_REGULAR.
Example 1. Sort multiple arraysCopy codeThe Code is as follows: <? Php
$ Ar1 = array ("Ten", 100,100, "");
$ Ar2 = array (1, 3, "2", 1 );
Array_multisort ($ ar1, $ ar2 );
Var_dump ($ ar1 );
Var_dump ($ ar2 );
?>

In this example, after sorting, the first array will contain "10", "a", 100,100. The second array will contain 1, 1, "2", 3. The project order in the second array is exactly the same as that in the first array (100 and 100.Copy codeThe Code is as follows: array (4 ){
[0] => string (2) "10"
[1] => string (1) ""
[2] => int (100)
[3] => int (100)
}
Array (4 ){
[0] => int (1)
[1] => int (1)
[2] => string (1) "2"
[3] => int (3)
}

Example 2. Sort multidimensional arraysCopy codeThe Code is as follows: <? Php
$ Ar = array ("10", 100,100, "a"), array (1, 3, "2", 1 ));
Array_multisort ($ ar [0], SORT_ASC, SORT_STRING,
$ Ar [1], SORT_NUMERIC, SORT_DESC );
?>

In this example, after sorting, the first array will contain 10,100,100, "a" (as the string Ascending Order), and the second array will contain 1, 3, "2 ", 1 (sort the values in descending order ).
Example 3. Sorting multi-dimen1_arrayCopy codeThe Code is as follows: <? Php
$ Ar = array (
Array ("10", 11,100,100, ""),
Array (1, 2, "2", 3, 1)
);
Array_multisort ($ ar [0], SORT_ASC, SORT_STRING,
$ Ar [1], SORT_NUMERIC, SORT_DESC );
Var_dump ($ ar );
?>

In this example, after sorting, the first array will become "10", 100,100, 11, "a" (sorted in ascending order as strings ). The second array will contain 1, 3, "2", 2, 1 (arranged in descending order as numbers ).Copy codeThe Code is as follows: array (2 ){
[0] => array (5 ){
[0] => string (2) "10"
[1] => int (100)
[2] => int (100)
[3] => int (11)
[4] => string (1) ""
}
[1] => array (5 ){
[0] => int (1)
[1] => int (3)
[2] => string (1) "2"
[3] => int (2)
[4] => int (1)
}
}

Example 4. Sort database results
In this example, each unit in the data array represents a row in a table. This is a collection of typical database records.
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, such as mysql_fetch_assoc ().Copy codeThe Code is as follows: <? Php
$ 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.Copy codeThe Code is as follows: <? Php
// Retrieve the column list
Foreach ($ data as $ key => $ row ){
$ Volume [$ key] = $ row ['Volume '];
$ Edition [$ key] = $ row ['version'];
}
// Sort data by volume in descending order and edition in ascending order
// Use $ data as the last parameter and sort it by a common key
Array_multisort ($ volume, SORT_DESC, $ edition, SORT_ASC, $ data );
?>

The data set is sorted as follows:
Volume | edition
------- + --------
98 | 2
86 | 1
86 | 6
85 | 6
67 | 2
67 | 7

Example 5. Sorting case-insensitive letters
Both SORT_STRING and SORT_REGULAR are case-sensitive letters. uppercase letters are placed before lowercase letters.
To sort the data in case-insensitive order, the data is sorted by copying the lowercase letters of the original array.Copy codeThe Code is as follows: <? Php
$ Array = array ('alpha', 'atomic ', 'beta', 'bank ');
$ Array_lowercase = array_map ('strlower ', $ array );
Array_multisort ($ array_lowercase, SORT_ASC, SORT_STRING, $ array );
Print_r ($ array );
?>

The above example will output:
Array
(
[0] => Alpha
[1] => atomic
[2] => bank
[3] => Beta
)

[Note] This function is quite useful. To help you understand it, let's look at the following example:
Example 6. Ranking
<? Php
$ Grade = array ("score" => array (70, 95, 70.0, 60, "70 "),
"Name" => array ("Zhang San", "Li Si", "Wang Wu ",
"Zhao Liu", "Liu Qi "));
Array_multisort ($ grade ["score"], SORT_NUMERIC, SORT_DESC,
// Take the score as a value, sorted from high to low
$ Grade ["name"], SORT_STRING, SORT_ASC );
// Use the name as a string in ascending order
Var_dump ($ grade );
?>
The above example will output:
Array (2 ){
["Score"] =>
Array (5 ){
[0] =>
Int (95)
[1] =>
String (2) "70"
[2] =>
Float (70)
[3] =>
Int (70)
[4] =>
Int (60)
}
["Name"] =>
Array (5 ){
[0] =>
String (5) "Li Si"
[1] =>
String (6) "Liu Qi"
[2] =>
String (7) "Wang Wu"
[3] =>
String (9) "Zhang San"
[4] =>
String (8) "Zhao Liu"
}
}
In this example, the $ grade array containing scores is sorted by score from high to low, and those with the same scores are sorted by name from small to large. After sorting, Li Si 95 is ranked first, while Zhao liu60 is ranked fifth without objection. Zhang San, Wang Wu, and Liu Qi both scored 70 points. Their rankings were alphabetically arranged by their names. Liu was in the front, Wang was in the back, and Zhang was in the end. For the difference, the three 70-minute values are represented by integers, floating-point numbers, and strings. The sorting results can be clearly seen in the program output.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.