Array_multisort: PHP multi-dimensional array sorting example _ PHP Tutorial

Source: Internet
Author: User
Tags sorted by name
Array_multisort provides an example of PHP multi-dimensional array sorting. Array_multisort-sort multiple arrays or multi-dimensional arrays. description: boolarray_multisort (arrayar1 [, mixedarg [, mixed... [, array...]) array_multisort (PHP4, PHP5) if array_multisort-sorts multiple arrays or multi-dimensional arrays
Description
Bool array_multisort (array ar1 [, mixed arg [, mixed... [, array...])

Array_multisort
(PHP 4, PHP 5)
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 arrays

$ Ar1 = array ("10", 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", and 100,100. The second array will contain, "2", 3. The project order in the second array is exactly the same as that in the first array (100 and 100.

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 arrays

$ 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, "2 ″, 1 (sort the values in descending order ).

Example 3. Sorting multi-dimen1_array

$ 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 ).

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 ().

$ 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.

// 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.

$ 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

$ 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.
Additional information:
The most complex sorting method for multi-dimensional array sorting in PHP language. In actual encoding, we will use the PHP function array_multisort () to implement this complex sorting. For example, first sort a nested array by a common keyword and then sort it by another keyword. This is very similar to sorting multiple fields using the SQL ORDER BY statement.
PHP function asort () is parsed using the specific method of value sorting
Detailed description of the features of the PHP function arsort ()
Introduction to features of PHP natural language sorting
PHP natural language inverted implementation method
How to use the PHP function usort () to implement custom sorting
The Listing J example illustrates how the PHP function array_multisort () works:
1, "name" => "Boney M", "rating" => 3), array ("id" => 2, "name" => "Take That ", "rating" => 1), array ("id" => 3, "name" => "The Killers", "rating" => 4 ), array ("id" => 4, "name" => "Lusain", "rating" => 3),); foreach ($ data as $ key => $ value) {$ name [$ key] = $ value [name]; $ rating [$ key] = $ value [rating];} array_multisort ($ rating, $ name, $ data ); print_r ($ data);?> Here, we simulate an array of rows and columns in the $ data array. Then, I use the PHP function array_multisort () to rearrange the data set. first, sort the data set by rating, and then sort the data by name if rating is equal. The output result is as follows:

The code is as follows:


Array ([0] => Array
(
[Id] => 2
[Name] => Take That
[Rating] => 1
) [1] => Array
(
[Id] => 1
[Name] => Boney M
[Rating] => 3
)
[2] => Array
(
[Id] => 4
[Name] => Lusain
[Rating] => 3
)
[3] => Array
(
[Id] => 3
[Name] => The Killers
[Rating] => 4
)
)


The PHP function array_multisort () is one of the most useful functions in PHP and has a wide range of applications. In addition, as you can see in the example, it can sort multiple irrelevant arrays, or use one of the elements as the basis for next sorting, you can also sort database result sets.

Http://www.bkjia.com/PHPjc/322689.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/322689.htmlTechArticlearray_multisort-sorting multiple arrays or multi-dimensional arrays description bool array_multisort (array ar1 [, mixed arg [, mixed... [, array...]) array_multisort (PHP 4, PHP 5) If...

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.