Home Backend Development PHP Tutorial How to sort multiple arrays or multidimensional arrays using the array_multisort function?

How to sort multiple arrays or multidimensional arrays using the array_multisort function?

Jun 26, 2017 am 11:33 AM
array use function how

array_multisort() can be used to sort multiple arrays at one time, or to sort multidimensional arrays according to a certain dimension or multiple dimensions.

array_multisort — Sort multiple arrays or multidimensional arrays
Description
bool array_multisort (array ar1 [, mixed arg [, mixed ... [, array ...]]] )
array_multisort
(PHP 4, PHP 5)
Returns TRUE if successful, returns FALSE if failed.
array_multisort() can be used to sort multiple arrays at once, or to sort multi-dimensional arrays according to one or more dimensions.
Associated (string) key names remain unchanged, but numeric key names 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 parameters of this function are somewhat unusual in structure, 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 flags:
SORT_ASC – Sort in ascending order

SORT_DESC – Sort in descending order
Sort type flags:
SORT_REGULAR – Sort Items are compared according to the usual method

SORT_NUMERIC – items are compared according to numeric values

SORT_STRING – items are compared according to strings
Cannot specify two similar items after each array sorting flag. The sort flags specified after each array are valid only for that array – before that the default values ​​SORT_ASC and SORT_REGULAR were used.

Example 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); 
?>
Copy after login

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) 
}
Copy after login

Example 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); 
?>
Copy after login

After sorting in this example, the first array will contain 10, 100, 100, "a" ( As strings sorted ascending), the second array will contain 1, 3, "2", 1 (as numeric sorting descending).
Example 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); 
?>
Copy after login

In this example, after sorting, the first array will become "10", 100, 100, 11, "a" (being treated as 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) 
} 
}
Copy after login

Example 4. Sort database results
In this example, each cell in the data array represents a row in a table. This is a typical collection of data recorded in a database.
The data in the example is as follows:
volume | edition
——-+——–
67 | 2
86 | 1
85 | 6
98 | 2
86 | 6
67 | 7
The data are all stored in an array named data. This is usually obtained from the database through a loop, such as mysql_fetch_assoc().

<?php 
$data[] = array(‘volume&#39; => 67, ‘edition&#39; => 2); 
$data[] = array(‘volume&#39; => 86, ‘edition&#39; => 1); 
$data[] = array(‘volume&#39; => 85, ‘edition&#39; => 6); 
$data[] = array(‘volume&#39; => 98, ‘edition&#39; => 2); 
$data[] = array(‘volume&#39; => 86, ‘edition&#39; => 6); 
$data[] = array(‘volume&#39; => 67, ‘edition&#39; => 7); 
?>
Copy after login

In this example, volume will be sorted in descending order and edition will be sorted in ascending order.
Now we have an array containing rows, but array_multisort() requires an array containing columns, so use the following code to get the columns and then sort them.

<?php 
// 取得列的列表 
foreach ($data as $key => $row) { 
$volume[$key] = $row[&#39;volume&#39;]; 
$edition[$key] = $row[&#39;edition&#39;]; 
} 
// 将数据根据 volume 降序排列,根据 edition 升序排列 
// 把 $data 作为最后一个参数,以通用键排序 
array_multisort($volume, SORT_DESC, $edition, SORT_ASC, $data); 
?>
Copy after login

The data collection is now sorted, and the results are as follows:

volume | edition
——-+——–
98 | 2
86 | 1
86 | 6
85 | 6
67 | 2
67 | 7

Example 5. Case-insensitive alphabetical sorting
SORT_STRING and SORT_REGULAR are both distinctions For uppercase and lowercase letters, uppercase letters will be sorted before lowercase letters.
To perform case-insensitive sorting, you must sort by a copy of the lowercase letters of the original array.

<?php 
$array = array(‘Alpha&#39;, ‘atomic&#39;, ‘Beta&#39;, ‘bank&#39;); 
$array_lowercase = array_map(&#39;strtolower&#39;, $array); 
array_multisort($array_lowercase, SORT_ASC, SORT_STRING, $array); 
print_r($array); 
?>
Copy after login

The above example will output:

Array 
( 
[0] => Alpha 
[1] => atomic 
[2] => bank 
[3] => Beta 
)
Copy after login

补充资料:
对于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 
) 
)
Copy after login

PHP函数array_multisort()是PHP中最有用的函数之一,它有非常广泛的应用范围。另外,就如你在例子中所看到的,它能对多个不相关的数组进行排序,也可以使用其中的一个元素作为下次排序的基础,还可以对数据库结果集进行排序。

The above is the detailed content of How to sort multiple arrays or multidimensional arrays using the array_multisort function?. For more information, please follow other related articles on the PHP Chinese website!

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 Article

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

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)

BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? Apr 26, 2024 am 09:40 AM

MetaMask (also called Little Fox Wallet in Chinese) is a free and well-received encryption wallet software. Currently, BTCC supports binding to the MetaMask wallet. After binding, you can use the MetaMask wallet to quickly log in, store value, buy coins, etc., and you can also get 20 USDT trial bonus for the first time binding. In the BTCCMetaMask wallet tutorial, we will introduce in detail how to register and use MetaMask, and how to bind and use the Little Fox wallet in BTCC. What is MetaMask wallet? With over 30 million users, MetaMask Little Fox Wallet is one of the most popular cryptocurrency wallets today. It is free to use and can be installed on the network as an extension

Tips for dynamically creating new functions in golang functions Tips for dynamically creating new functions in golang functions Apr 25, 2024 pm 02:39 PM

Go language provides two dynamic function creation technologies: closure and reflection. closures allow access to variables within the closure scope, and reflection can create new functions using the FuncOf function. These technologies are useful in customizing HTTP routers, implementing highly customizable systems, and building pluggable components.

Considerations for parameter order in C++ function naming Considerations for parameter order in C++ function naming Apr 24, 2024 pm 04:21 PM

In C++ function naming, it is crucial to consider parameter order to improve readability, reduce errors, and facilitate refactoring. Common parameter order conventions include: action-object, object-action, semantic meaning, and standard library compliance. The optimal order depends on the purpose of the function, parameter types, potential confusion, and language conventions.

How to write efficient and maintainable functions in Java? How to write efficient and maintainable functions in Java? Apr 24, 2024 am 11:33 AM

The key to writing efficient and maintainable Java functions is: keep it simple. Use meaningful naming. Handle special situations. Use appropriate visibility.

Complete collection of excel function formulas Complete collection of excel function formulas May 07, 2024 pm 12:04 PM

1. The SUM function is used to sum the numbers in a column or a group of cells, for example: =SUM(A1:J10). 2. The AVERAGE function is used to calculate the average of the numbers in a column or a group of cells, for example: =AVERAGE(A1:A10). 3. COUNT function, used to count the number of numbers or text in a column or a group of cells, for example: =COUNT(A1:A10) 4. IF function, used to make logical judgments based on specified conditions and return the corresponding result.

Comparison of the advantages and disadvantages of C++ function default parameters and variable parameters Comparison of the advantages and disadvantages of C++ function default parameters and variable parameters Apr 21, 2024 am 10:21 AM

The advantages of default parameters in C++ functions include simplifying calls, enhancing readability, and avoiding errors. The disadvantages are limited flexibility and naming restrictions. Advantages of variadic parameters include unlimited flexibility and dynamic binding. Disadvantages include greater complexity, implicit type conversions, and difficulty in debugging.

What are the benefits of C++ functions returning reference types? What are the benefits of C++ functions returning reference types? Apr 20, 2024 pm 09:12 PM

The benefits of functions returning reference types in C++ include: Performance improvements: Passing by reference avoids object copying, thus saving memory and time. Direct modification: The caller can directly modify the returned reference object without reassigning it. Code simplicity: Passing by reference simplifies the code and requires no additional assignment operations.

C++ Function Exception Advanced: Customized Error Handling C++ Function Exception Advanced: Customized Error Handling May 01, 2024 pm 06:39 PM

Exception handling in C++ can be enhanced through custom exception classes that provide specific error messages, contextual information, and perform custom actions based on the error type. Define an exception class inherited from std::exception to provide specific error information. Use the throw keyword to throw a custom exception. Use dynamic_cast in a try-catch block to convert the caught exception to a custom exception type. In the actual case, the open_file function throws a FileNotFoundException exception. Catching and handling the exception can provide a more specific error message.

See all articles