Home Backend Development PHP Tutorial php关于array_multisort多维数组排序的使用说明_php技巧

php关于array_multisort多维数组排序的使用说明_php技巧

May 17, 2016 am 09:21 AM
array_multisort

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

$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 of this Website
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

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 Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

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,

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

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 permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

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

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

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

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

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

Framework Security Features: Protecting against vulnerabilities. Framework Security Features: Protecting against vulnerabilities. Mar 28, 2025 pm 05:11 PM

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

See all articles