Notes on the use of PHP array_multisort() function
Function bool array_multisort (array &$arr [, mixed $arg = SORT_ASC [, mixed $arg = SORT_REGULAR [, mixed $...]]] )
Parameter description: The function sorts multiple arrays or multidimensional arrays Sorting
The first parameter is an array, and each subsequent parameter may be an array or the following sort order flag
SORT_ASC - Default, sort in ascending order
SORT_DESC - Sort in descending order
You can then specify the sorting type
SORT_REGULAR - default. Arrange each item in regular order.
SORT_NUMERIC - Sort each item in numerical order.
SORT_STRING - Sort each item in alphabetical order.
Example code
$arr1 = array('10', 11, 100, 100, 'a'); $arr2 = array(1, 2, 3, '2', 5); array_multisort($arr1, $arr2);
The result is:
$arr1
Array ([0] => 10 [1] => a [2] => 11 [3] = > 100 [4] => 100 )
# '10' is converted to an integer 10 when compared with 11, 100, 100, which is smaller than the other three numbers
# '10' is when compared with 'a' As a string, its first character '1' has an ascii code value of 49 which is less than 'a' (the ascii value is 97), so '10' is the smallest element
# 'a' lies in the comparison of the other three numbers, Convert to integer 0, less than the other three numbers
$arr2
Array ( [0] => 1 [1] => 5 [2] => 2 [3] => 2 [4 ] => 3 )
# $arr2 element 1 corresponds to $arr1 element '10' position, so it is ranked at [0] position
# $arr1[2] => 100, $arr1[3] => 100 corresponds to $arr2 elements 3 and '2' respectively. 3 is greater than '2', so the $arr1[2] corresponding to 2 => 100's sorted subscript is
3, and the $arr1[3] corresponding to 3 => 100's sorted subscript is 4
Summary
1. The number of array elements participating in the sorting remains the same
2. The positions of the sorted array elements correspond to, for example, '10' => 1, 11 => 2
3. The following arrays Sort based on the order of the previous array
4. If the previous array encounters equal elements, compare the following array
array_multisort — Sort multiple arrays or multi-dimensional arrays
Description
bool array_multisort (array $ar1 [, mixed $arg [, mixed $... [, array $... ]]] )
Returns TRUE on success, or returns FALSE on failure.
array_multisort() can be used to sort multiple arrays at once, or to sort multi-dimensional arrays according to one or more dimensions.
The associated (string) key name remains unchanged, but the numeric key name will be re-indexed.
The input array is treated as a table column and sorted by row - this is similar to the functionality of SQL's ORDER BY clause. The first array is the main array to be sorted. If the rows (values) in the array are compared to be the same, they are sorted according to the size of the corresponding value in the next input array, and so on.
The parameter structure of this function is somewhat unusual, but very flexible. The first parameter must be an array. Each of the following parameters can be an array or a sort flag listed below.
Sort order flag:
SORT_ASC - Sort in ascending order
SORT_DESC - Sort in descending order
Sort type flag:
SORT_REGULAR - Sort Items are compared according to the usual method
SORT_NUMERIC - compare items according to numeric values
SORT_STRING - compare items according to strings
Two similar sorting flags cannot be specified after each array. The sort flags specified after each array are valid only for that array - before that, the default values SORT_ASC and SORT_REGULAR.
#1 Sort multiple arrays
<?php $ar1 = array("10", 100, 100, "a"); $ar2 = array(1, 3, "2", 1); array_multisort($ar1, $ar2); var_dump($ar1); var_dump($ar2); ?>
After sorting in this example, the first array will contain "10", "a", 100, 100. The second array will contain 1,1,"2",3. The order of the items in the second array is exactly the same as the order of the corresponding items (100 and 100) in the first array.
array(4) { [0]=> string(2) "10" [1]=> string(1) "a" [2]=> int(100) [3]=> int(100) } array(4) { [0]=> int(1) [1]=> int(1) [2]=> string(1) "2" [3]=> int(3) }
#2 Sorting multi-dimensional arrays
<?php $ar = array (array ("10", 100, 100, "a"), array (1, 3, "2", 1)); array_multisort ($ar[0], SORT_ASC, SORT_STRING, $ar[1], SORT_NUMERIC, SORT_DESC); ?>
After sorting in this example, the first array will contain 10, 100, 100, "a" (as a string ascending sort), The second array will contain 1, 3, "2", 1 (as numerical descending order).
#3 Sorting multi-dimensional array
<?php $ar = array( array("10", 11, 100, 100, "a"), 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" (used as Sort the strings in ascending order). The second array will contain 1, 3, "2", 2, 1 (treated as numbers in descending order).
array(2) { [0]=> array(5) { [0]=> string(2) "10" [1]=> int(100) [2]=> int(100) [3]=> int(11) [4]=> string(1) "a" } [1]=> array(5) { [0]=> int(1) [1]=> int(3) [2]=> string(1) "2" [3]=> int(2) [4]=> int(1) } }
#4 对数据库结果进行排序
本例中 data 数组中的每个单元表示一个表中的一行。这是典型的数据库记录的数据集合。
例子中的数据如下:
volume | edition
-------+--------
67 | 2
86 | 1
85 | 6
98 | 2
86 | 6
67 | 7
数据全都存放在名为 data 的数组中。这通常是通过循环从数据库取得的结果,例如 mysql_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);
?>
本例中将把 volume 降序排列,把 edition 升序排列。
现在有了包含有行的数组,但是 array_multisort() 需要一个包含列的数组,因此用以下代码来取得列,然后排序。
// 取得列的列表
foreach ($data as $key => $row) {
$volume[$key] = $row['volume'];
$edition[$key] = $row['edition'];
}
// 将数据根据 volume 降序排列,根据 edition 升序排列
// 把 $data 作为最后一个参数,以通用键排序
array_multisort($volume, SORT_DESC, $edition, SORT_ASC, $data);
?>
数据集合现在排好序了,结果如下:
volume | edition
-------+--------
98 | 2
86 | 1
86 | 6
85 | 6
67 | 2
67 | 7
Example #5 不区分大小写字母排序
SORT_STRING 和 SORT_REGULAR 都是区分大小写字母的,大写字母会排在小写字母之前。
要进行不区分大小写的排序,就要按照原数组的小写字母拷贝来排序。
<?php $array = array('Alpha', 'atomic', 'Beta', 'bank'); $array_lowercase = array_map('strtolower', $array); array_multisort($array_lowercase, SORT_ASC, SORT_STRING, $array); print_r($array); ?>
以上例程会输出:
Array
(
[0] => Alpha
[1] => atomic
[2] => bank
[3] => Beta
)
【译者注】本函数相当有用,为有助于理解,请再看下面这个例子:
Example #6 名次排列
<?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, // 将分数作为数值,由高到低排序 $grade["name"], SORT_STRING, SORT_ASC); // 将名字作为字符串,由小到大排序 var_dump($grade); ?>
以上例程会输出:
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"
}
}
本例中对包含成绩的数组 $grade 按照分数(score)由高到低进行排序,分数相同的人则按照名字(name)由小到大排序。排序后李四 95 分为第一名,赵六 60 分为第五名没有异议。张三、王五和刘七都是 70 分,他们的名次则由其姓名的字母顺序排列,Liu 在前,Wang 在后而 Zhang 在最后。为了区别,三个 70 分分别用了整数,浮点数和字符串来表示,可以在程序输出中清楚地看到它们排序的结果。
更多PHP array_multisort()函数的使用札记相关文章请关注PHP中文网!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.
