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

Alipay PHP...

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...
