search
HomeBackend DevelopmentPHP Tutorialphp array_multisort() multi-array sorting method_PHP tutorial

In php, array_multisort() can sort multiple arrays at one time, or sort multi-dimensional arrays according to a certain dimension or multiple dimensions. It returns TRUE if successful and FALSE if failed.

bool array_multisort (array ar1 [, mixed arg [, mixed ... [, array ...]]] )

Returns TRUE if successful, 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.


Example 1. Sort multidimensional array

The code is as follows Copy code
 代码如下 复制代码

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

$ar = array( array("10", 11, 100, 100, "a"),
 代码如下 复制代码

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

array( 1, 2, "2", 3, 1)

);

array_multisort($ar[0], SORT_ASC, SORT_STRING,

                    $ar[1], SORT_NUMERIC, SORT_DESC);

var_dump($ar);
 代码如下 复制代码

$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 transform to "10", 100, 100, 11, "a" (it was sorted as strings in ascending order). The second will contain 1, 3, "2 ", 2, 1 (sorted as numbers, in descending order).
The code is as follows Copy code
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) } }
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 2. Sorting multi-dimensional array
The code is as follows Copy code
$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 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)
  }
}
 

Example 3 Let’s take a comprehensive look at an example commonly used in applications.

 代码如下 复制代码

header('Content-Type: text/html; charset=utf-8');
echo '
'; <br>
//原始数组格式 <br>
$array = array( <br>
'key1' => array( <br>
'item1' => '65', <br>
'item2' => '35', <br>
'item3' => '84', <br>
), <br>
'key2' => array( <br>
'item1' => '24', <br>
), <br>
'key3' => array( <br>
'item1' => '38', <br>
'item3' => '45', <br>
), <br>
); <br>
//要排序的键 <br>
//按照数组中的 item1进行排序 <br>
//你也可以换成item2 <br>
$sort = 'item1'; <br>
foreach($array as $k => $v) <br>
{ <br>
$newArr[$k] = $v[$sort]; <br>
} <br>
//这个函数如果执行正确他会直接改变原数组键值的顺序 <br>
//如果执行失败,那么他会返回 bool(false) <br>
array_multisort($newArr,SORT_DESC, $array); <br>
var_dump($array); <br>
//---------------------排序后的数组打印效果 开始-------------------- <br>
array(3) { <br>
["key1"]=> <br>
array(3) { <br>
["item1"]=> <br>
string(2) "65" <br>
["item2"]=> <br>
string(2) "35" <br>
["item3"]=> <br>
string(2) "84" <br>
} <br>
["key3"]=> <br>
array(2) { <br>
["item1"]=> <br>
string(2) "38" <br>
["item3"]=> <br>
string(2) "45" <br>
} <br>
["key2"]=> <br>
array(1) { <br>
["item1"]=> <br>
string(2) "24" <br>
} <br>
} <br>
//---------------------排序后的数组打印效果 结束---------------------

For a detailed explanation of the array_multisort() function, please refer to http://www.bKjia.c0m/phper/php-function/39192.htm

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/629150.htmlTechArticleIn php, array_multisort() can sort multiple arrays at one time, or sort them according to a certain dimension or multiple dimensions. Sort multidimensional arrays, returning TRUE if successful, and FALSE if failed. ...
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 Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot 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

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools