search
HomeBackend DevelopmentPHP Tutorialphp关于array_multisort多维数组排序的使用说明_php技巧

一、先看最简单的情况。有两个数组:
复制代码 代码如下:

$arr1 = array(1,9,5);
$arr2 = array(6,2,4);
array_multisort($arr1,$arr2);
print_r($arr1); // 得到的顺序是1,5,9
print_r($arr2); // 得到的顺序是6,4,2

我估计两个数组的值自始至终都是对应着的:1对应6,9对应2,5对应4。
我们再加多一个数组看看会怎样:
复制代码 代码如下:

$arr1 = array(1,9,5);
$arr2 = array(6,2,4);
$arr3 = array(3,7,8);
array_multisort($arr1,$arr2,$arr3);

查看结果,1自始至终都对应6对应3,其它项也是如此。这种对应关系就是手册中所谓的“排序时保留原有的键名关联”。
另外也可以把每个数组想像成数据库表的一列。而对应着的1,6,3为一数据行,9,2,7为另一数据行。。。
array_multisort会先按第一个数组(想像成列)排序,如果第一个数组(列)的值相同,则按第二个数组(列)排序。
具体可以用下面的程式来测试:
复制代码 代码如下:

$arr1 = array(1,9,5,9);
$arr2 = array(6,2,4,1);
$arr3 = array(3,7,8,0);
array_multisort($arr1,$arr2,$arr3);

可以想像这里$arr3的结果是(3,8,0,7)。
二、接下来讲解array_multisort的参数。这个函数的参数很灵活。最简单的情况是如上面所示的以1个或n个数组作为参数,需要注意的是每个数组的项数要一样,否则会warning导致排序失效。
像这样array_multisort($arr1,$arr2,$arr3); 默认是所有数组都是升序排列,如果想对$arr2降序,并当作字符串去比较,就要写成:
array_multisort($arr1, $arr2, SORT_DESC, SORT_STRING, $arr3);
每个array后面可以跟一个排序顺序标志或一个排序类型标志,或者两种标志同时出现。但是每种排序标志在每个数组后面只能出现一个。
详细如下:
排序顺序标志:

SORT_ASC - 按照上升顺序排序(默认)
SORT_DESC - 按照下降顺序排序

排序类型标志:

SORT_REGULAR - 将项目按照通常方法比较(默认)
SORT_NUMERIC - 将项目按照数值比较
SORT_STRING - 将项目按照字符串比较

三、最后是array_multisort有什么实际作用。
我们通常有一些多维数组需要排序:
$guys = Array
(
[0] => Array
(
[name] => jake
[score] => 80
[grade] => A
)
[1] => Array
(
[name] => jin
[score] => 70
[grade] => A
)
[2] => Array
(
[name] => john
[score] => 80
[grade] => A
)
[3] => Array
(
[name] => ben
[score] => 20
[grade] => B
)
)
例如我们想按成绩倒序排列,如果成绩相同就按名字的升序排列。这时我们就需要根据$guys的顺序多弄两个数组出来:$scores = array(80,70,80,20);$names = array('jake','jin','john','ben');然后array_multisort($scores, SORT_DESC, $names, $guys);就行了还能不能更灵活一点呢,每次想排序都要另外弄些数组出来吗?其实在qeephp的helper_array类里面已经封装得很好,下面是它的两个方法,需要的人自己修改一下就可以用了:
复制代码 代码如下:

/**
* 根据指定的键对数组排序
*
* 用法:
* @code php
* $rows = array(
* array('id' => 1, 'value' => '1-1', 'parent' => 1),
* array('id' => 2, 'value' => '2-1', 'parent' => 1),
* array('id' => 3, 'value' => '3-1', 'parent' => 1),
* array('id' => 4, 'value' => '4-1', 'parent' => 2),
* array('id' => 5, 'value' => '5-1', 'parent' => 2),
* array('id' => 6, 'value' => '6-1', 'parent' => 3),
* );
*
* $rows = Helper_Array::sortByCol($rows, 'id', SORT_DESC);
* dump($rows);
* // 输出结果为:
* // array(
* // array('id' => 6, 'value' => '6-1', 'parent' => 3),
* // array('id' => 5, 'value' => '5-1', 'parent' => 2),
* // array('id' => 4, 'value' => '4-1', 'parent' => 2),
* // array('id' => 3, 'value' => '3-1', 'parent' => 1),
* // array('id' => 2, 'value' => '2-1', 'parent' => 1),
* // array('id' => 1, 'value' => '1-1', 'parent' => 1),
* // )
* @endcode
*
* @param array $array 要排序的数组
* @param string $keyname 排序的键
* @param int $dir 排序方向
*
* @return array 排序后的数组
*/
static function sortByCol($array, $keyname, $dir = SORT_ASC)
{
return self::sortByMultiCols($array, array($keyname => $dir));
} /**
* 将一个二维数组按照多个列进行排序,类似 SQL 语句中的 ORDER BY
*
* 用法:
* @code php
* $rows = Helper_Array::sortByMultiCols($rows, array(
* 'parent' => SORT_ASC,
* 'name' => SORT_DESC,
* ));
* @endcode
*
* @param array $rowset 要排序的数组
* @param array $args 排序的键
*
* @return array 排序后的数组
*/
static function sortByMultiCols($rowset, $args)
{
$sortArray = array();
$sortRule = '';
foreach ($args as $sortField => $sortDir)
{
foreach ($rowset as $offset => $row)
{
$sortArray[$sortField][$offset] = $row[$sortField];
}
$sortRule .= '$sortArray[\'' . $sortField . '\'], ' . $sortDir . ', ';
}
if (empty($sortArray) || empty($sortRule)) { return $rowset; }
eval('array_multisort(' . $sortRule . '$rowset);');
return $rowset;
}

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP vs. Python: Understanding the DifferencesPHP vs. Python: Understanding the DifferencesApr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP: Is It Dying or Simply Adapting?PHP: Is It Dying or Simply Adapting?Apr 11, 2025 am 12:13 AM

PHP is not dying, but constantly adapting and evolving. 1) PHP has undergone multiple version iterations since 1994 to adapt to new technology trends. 2) It is currently widely used in e-commerce, content management systems and other fields. 3) PHP8 introduces JIT compiler and other functions to improve performance and modernization. 4) Use OPcache and follow PSR-12 standards to optimize performance and code quality.

The Future of PHP: Adaptations and InnovationsThe Future of PHP: Adaptations and InnovationsApr 11, 2025 am 12:01 AM

The future of PHP will be achieved by adapting to new technology trends and introducing innovative features: 1) Adapting to cloud computing, containerization and microservice architectures, supporting Docker and Kubernetes; 2) introducing JIT compilers and enumeration types to improve performance and data processing efficiency; 3) Continuously optimize performance and promote best practices.

When would you use a trait versus an abstract class or interface in PHP?When would you use a trait versus an abstract class or interface in PHP?Apr 10, 2025 am 09:39 AM

In PHP, trait is suitable for situations where method reuse is required but not suitable for inheritance. 1) Trait allows multiplexing methods in classes to avoid multiple inheritance complexity. 2) When using trait, you need to pay attention to method conflicts, which can be resolved through the alternative and as keywords. 3) Overuse of trait should be avoided and its single responsibility should be maintained to optimize performance and improve code maintainability.

What is a Dependency Injection Container (DIC) and why use one in PHP?What is a Dependency Injection Container (DIC) and why use one in PHP?Apr 10, 2025 am 09:38 AM

Dependency Injection Container (DIC) is a tool that manages and provides object dependencies for use in PHP projects. The main benefits of DIC include: 1. Decoupling, making components independent, and the code is easy to maintain and test; 2. Flexibility, easy to replace or modify dependencies; 3. Testability, convenient for injecting mock objects for unit testing.

Explain the SPL SplFixedArray and its performance characteristics compared to regular PHP arrays.Explain the SPL SplFixedArray and its performance characteristics compared to regular PHP arrays.Apr 10, 2025 am 09:37 AM

SplFixedArray is a fixed-size array in PHP, suitable for scenarios where high performance and low memory usage are required. 1) It needs to specify the size when creating to avoid the overhead caused by dynamic adjustment. 2) Based on C language array, directly operates memory and fast access speed. 3) Suitable for large-scale data processing and memory-sensitive environments, but it needs to be used with caution because its size is fixed.

How does PHP handle file uploads securely?How does PHP handle file uploads securely?Apr 10, 2025 am 09:37 AM

PHP handles file uploads through the $\_FILES variable. The methods to ensure security include: 1. Check upload errors, 2. Verify file type and size, 3. Prevent file overwriting, 4. Move files to a permanent storage location.

What is the Null Coalescing Operator (??) and Null Coalescing Assignment Operator (??=)?What is the Null Coalescing Operator (??) and Null Coalescing Assignment Operator (??=)?Apr 10, 2025 am 09:33 AM

In JavaScript, you can use NullCoalescingOperator(??) and NullCoalescingAssignmentOperator(??=). 1.??Returns the first non-null or non-undefined operand. 2.??= Assign the variable to the value of the right operand, but only if the variable is null or undefined. These operators simplify code logic, improve readability and performance.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.