array_multisort实现PHP多维数组排序示例讲解_php技巧
array_multisort — 对多个数组或多维数组进行排序
说明
bool array_multisort ( array ar1 [, mixed arg [, mixed ... [, array ...]]] )
array_multisort
(PHP 4, PHP 5)
如果成功则返回 TRUE,失败则返回 FALSE。
array_multisort() 可以用来一次对多个数组进行排序,或者根据某一维或多维对多维数组进行排序。
关联(string)键名保持不变,但数字键名会被重新索引。
输入数组被当成一个表的列并以行来排序――这类似于 SQL 的 ORDER BY 子句的功能。第一个数组是要排序的主要数组。数组中的行(值)比较为相同的话就按照下一个输入数组中相应值的大小来排序,依此类推。
本函数的参数结构有些不同寻常,但是非常灵活。第一个参数必须是一个数组。接下来的每个参数可以是数组或者是下面列出的排序标志。
排序顺序标志:
SORT_ASC – 按照上升顺序排序
SORT_DESC – 按照下降顺序排序
排序类型标志:
SORT_REGULAR – 将项目按照通常方法比较
SORT_NUMERIC – 将项目按照数值比较
SORT_STRING – 将项目按照字符串比较
每个数组之后不能指定两个同类的排序标志。每个数组后指定的排序标志仅对该数组有效 – 在此之前为默认值 SORT_ASC 和 SORT_REGULAR。
例子 1. 对多个数组排序
$ar1 = array(“10″, 100, 100, “a”);
$ar2 = array(1, 3, “2″, 1);
array_multisort($ar1, $ar2);
var_dump($ar1);
var_dump($ar2);
?>
本例中经过排序后,第一个数组将包含 “10″,”a”,100,100。第二个数组将包含 1,1,”2″,3。第二个数组中的项目顺序完全和第一个数组中相应的项目(100 和 100)顺序一致。
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. 对多维数组排序
$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);
?>
本例中经过排序后,第一个数组将包含 10,100,100,”a”(作为字符串上升排序),第二个数组将包含 1,3,”2″,1(作为数值下降排序)。
例子 3. Sorting multi-dimensional array
$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);
?>
本例中在排序后,第一个数组将变成 “10″,100,100,11,”a”(被当作字符串以升序排列)。第二个数组将包含 1, 3, “2″, 2, 1(被当作数字以降序排列)。
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
例子 5. 不区分大小写字母排序
SORT_STRING 和 SORT_REGULAR 都是区分大小写字母的,大写字母会排在小写字母之前。
要进行不区分大小写的排序,就要按照原数组的小写字母拷贝来排序。
$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
)
【译者注】本函数相当有用,为有助于理解,请再看下面这个例子:
例子 6. 名次排列
$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语言中的多维数组排序时最为复杂的一个排序方式。我们在实际编码中将会用到PHP函数array_multisort()来实现这一复杂的排序。例如,首先对一个嵌套数组使用一个普通的关键字进行排序,然后再根据另一个关键字进行排序。这与使用SQL的ORDER BY语句对多个字段进行排序非常相似。
PHP函数asort()利用值排序的具体方式解析
PHP函数arsort()的功能特点详解
PHP自然语言排序的特点介绍
PHP自然语言倒序的具体实现方式
如何运用PHP函数usort()实现自定义排序
Listing J示例为我们具体说明了PHP函数array_multisort()的工作方式:
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);?> 这里,我们在$data数组中模拟了一个行和列数组。然后,我使用PHP函数array_multisort()对数据集合进行重排,首先是根据rating进行排序,然后,如果rating相等的话,再根据name排序。它的输出结果如下:
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
)
)
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 debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

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

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.

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.
