search
HomeBackend DevelopmentPHP TutorialArray_multisort implements PHP multi-dimensional array sorting example explanation_PHP tutorial

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

Associative (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 parameter structure of this function is somewhat unusual, but very flexible. The first parameter must be an array. Each of the following arguments 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 - Compare items in the usual way

SORT_NUMERIC - Compare items based on numeric values ​​

SORT_STRING - Compare items based on 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 were used.

Example 1. Sort multiple arrays

$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)
}



Example 2. Sort multi-dimensional array

$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 ascending order of strings), and the second array will contain 1, 3, "2", 1 (as numerically descending order).

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

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



Example 4. Sorting 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 the array named data. This is usually obtained from the database through a loop, such as 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);
?>

In this example, the volume will be sorted in descending order and the edition will be sorted in ascending order.

Now you have an array with rows, but array_multisort() requires an array with columns, so use the following code to get the columns and then sort them.

// Get the list of columns
foreach ($data as $key => $row) {
$volume[$key] = $row[' volume'];
$edition[$key] = $row['edition'];
}

// Sort the data in descending order according to volume and in ascending order according to edition
// Sort by common key with $data as last parameter
array_multisort($volume, SORT_DESC, $edition, SORT_ASC, $data);
?>

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

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



Example 5. Case-insensitive sorting

SORT_STRING and SORT_REGULAR are both case-sensitive, and uppercase letters will Comes before lowercase letters.

To perform case-insensitive sorting, sort by lowercase letters of the original array.

$array = array('Alpha', 'atomic', 'Beta', 'bank');
$array_lowercase = array_map('strtolower', $array) ;

array_multisort($array_lowercase, SORT_ASC, SORT_STRING, $array);

print_r($array);
?>

The above example will output:

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



[Translator’s Note] This function is quite useful. To help you understand, please look at the following example:

Example 6. Ranking

$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,
// Use scores as numerical values, sort from high to low
$grade["name"], SORT_STRING, SORT_ASC);
// Use names as strings, sort from small to large
var_dump($ grade);
?>

The above example will output:

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”
}
}

In this example, the array $grade containing grades is sorted from high to low by score (score), and people with the same score are sorted by name ( name) in ascending order. After sorting, Li Si ranked first with 95 points, and Zhao Liu ranked fifth with 60 points. There is no objection. Zhang San, Wang Wu and Liu Qi all scored 70 points, and their rankings were arranged alphabetically by their names, with Liu first, Wang second and Zhang last. For the sake of distinction, the three 70 points are represented by integers, floating point numbers and strings respectively, and their sorted results can be clearly seen in the program output.
Supplementary information:
The most complicated sorting method for multi-dimensional array sorting in PHP language. We will use the PHP function array_multisort() in actual coding to implement this complex sorting. For example, a nested array is first sorted using a common key and then sorted based on another key. This is very similar to using SQL's ORDER BY statement to sort multiple fields.
The PHP function asort() analyzes the specific way of sorting by value
Detailed explanation of the functional characteristics of the PHP function asort()
Introduction to the characteristics of PHP natural language sorting
The specific implementation method of PHP natural language reverse order
How to use the PHP function usort() to implement custom sorting
The Listing J example explains for us how the PHP function array_multisort() works:
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);?> Here, we simulate a row and column array in the $data array. I then use the PHP function array_multisort() to reorder the data set, first by rating, and then, if the ratings are equal, by name. Its output is as follows:

Copy code The code is as follows:

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

The PHP function array_multisort() is one of the most useful functions in PHP and has a very wide range of applications. In addition, as you can see in the example, it can sort multiple unrelated arrays, it can also use one element as the basis for the next sort, and it can also sort database result sets.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/322689.htmlTechArticlearray_multisort — Instructions for sorting multiple arrays or multidimensional arrays bool array_multisort ( array ar1 [, mixed arg [, mixed ... [, array ...]]] ) array_multisort (PHP 4, PHP 5) if...
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 in Action: Real-World Examples and ApplicationsPHP in Action: Real-World Examples and ApplicationsApr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: Creating Interactive Web Content with EasePHP: Creating Interactive Web Content with EaseApr 14, 2025 am 12:15 AM

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python: Comparing Two Popular Programming LanguagesPHP and Python: Comparing Two Popular Programming LanguagesApr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

The Enduring Relevance of PHP: Is It Still Alive?The Enduring Relevance of PHP: Is It Still Alive?Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP's Current Status: A Look at Web Development TrendsPHP's Current Status: A Look at Web Development TrendsApr 13, 2025 am 12:20 AM

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP vs. Other Languages: A ComparisonPHP vs. Other Languages: A ComparisonApr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and FunctionalityPHP vs. Python: Core Features and FunctionalityApr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP: A Key Language for Web DevelopmentPHP: A Key Language for Web DevelopmentApr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

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
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

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.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

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

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),