Home php教程 PHP源码 php多维数组排序方法

php多维数组排序方法

Jun 08, 2016 pm 05:24 PM
array gt quot sort

本文章详细的介绍了关于多维数组排序的方法,array_multisort()这个函数可以对多个PHP数组进行排序,排序结果是所有的数组都按第一个数组的顺序进行排列——有点拗口,真的,并且我要只是这样说你一定也不明白。

<script>ec(2);</script>

先举个例子:

例如array_multisort($a,$b),$a,$b是两个数组,如果排序之后,$a数组的第3个元素被排到了第一位,那么$b的第三个元素不管他在$b中的大小都会排在第一位。看看下边的程序运行结果:

 

 代码如下 复制代码

$a =array(100,80,50,10,0);
$b = array("c","f","q","e","z");
array_multisort($a,$b);
var_dump($a);
var_dump($b);
?>

运行结果:
array(5) { [0]=> int(0) [1]=> int(10) [2]=> int(50) [3]=> int(80) [4]=> int(100) }
array(5) { [0]=> string(1) “z” [1]=> string(1) “e” [2]=> string(1) “q” [3]=> string(1) “f” [4]=> string(1) “c” }

很显然本来是数组b第五个元素的z被排到了第一位!

其实说明白了就是,array_multisort()先把第一个数组按照键值的大小排序,然后其它数组都按照第一个数组的调整策略进行调整——第三个元素放到第一位,第二个元素放到第二位……——其实这个多维数组排序算法的最基本体现!

不过需要注意的是:两个数组的元素个数必须相同,不然就会出现一个警告信息:
Warning: array_multisort() [function.array-multisort]: Array sizes are inconsistent in ……

好了,希望上边的大家也能用上,咱们还是说主要的吧:array_multisort()对多维数组进行排序,这个功能将来做项目的时候是非常有用的!

首先我们看看对多维数组的每一元素[数组]进行排序的操作方法,很简单,但是有几个参数需要说明一下,如果您对sql有所了解一看估计就明白了:

 

 代码如下 复制代码
//让我们来构造一个多维数组
$a=array(100,2,4,7,7);
$b=array('ab','ac','ad','ag','ap');
 
$ab = array($a,$b);
//开始排序
array_multisort($ab[0],SORT_NUMERIC,SORT_DESC,$ab[1],SORT_STRING,SORT_ASC);
print_r($ab);
?>

说明一下:首先我们用SORT_NUMERIC来声明对$ab[0]用数字类型排序,用SORT_DESC
声明顺序是逆序(从大到小),然后我们对$ab[1]用字符串类型排序,顺序是升序(顺序)
最后数组$ab的排序结果是两者的结合,先按$ab[0]的逆序,如果$ab[0]中存在大小相同的数值则按照$ab[1]的顺序排列,输出结果如下:

 代码如下 复制代码
Array (
[0] => Array ( [0] => 100 [1] => 7 [2] => 7 [3] => 4 [4] => 2 )
[1] => Array ( [0] => ab [1] => ag [2] => ap [3] => ad [4] => ac )
)

是不是很像在数据库中用order by?其实真的差不多!

现在我们再看一个更加贴近实际应用的例子:

 代码如下 复制代码

  $array[] = array("age"=>20,"name"=>"li");
$array[] = array("age"=>21,"name"=>"ai");
$array[] = array("age"=>20,"name"=>"ci");
$array[] = array("age"=>22,"name"=>"di");
 
foreach ($array as $key=>$value){
 $age[$key] = $value['age'];
 $name[$key] = $value['name'];
}
 
array_multisort($age,SORT_NUMERIC,SORT_DESC,$name,SORT_STRING,SORT_ASC,$array);
print_r($array);
?>

这个例子的$array[]数组,是按照数据库中读出的记录来构造的,我们现在对他们按照年龄从大到小的顺序排列,如果年龄相同就按照名字的顺序排序。这样的排序才是我们将来会经常用的到的,
因为array_multisort()需要的排序参数必须是一个列,所以我们用foreach把这个数组的年龄和姓名读出来,之后呢?
就像上边的例子一样,进行排序,最后一个参数$array想必大家也看见了,是的这里需要声明对哪个数组进行排序,因为我们前边两个参数在形式上已经和需要排序的PHP数组没有关系了,虽然其实他们就是$array中的数据——我们从$array中抽取的列——排序当然是需要列,还没见过用行数据进行排序的呢!

输出结果如下——正如我们所想的:

 代码如下 复制代码
Array (
[0] => Array ( [age] => 22 [name] => di )
[1] => Array ( [age] => 21 [name] => ai )
[2] => Array ( [age] => 20 [name] => ci )
[3] => Array ( [age] => 20 [name] => li )
)

看到了吧,其实也很简单,就是那几个需要大写的参数有点烦人而已!虽说也有点难以理解,但是理解了就好了,将来很有用的哦!
附录:
排序顺序标志:

SORT_ASC – 按照上升顺序排序
SORT_DESC – 按照下降顺序排序

排序类型标志:

SORT_REGULAR – 将项目按照通常方法比较
SORT_NUMERIC – 将项目按照数值比较
SORT_STRING – 将项目按照字符串比较

每个数组之后不能指定两个同类的排序标志。每个数组后指定的排序标志仅对该数组有效 – 在此之前为默认值 SORT_ASC 和 SORT_REGULAR。

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)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 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)

What are the differences between Huawei GT3 Pro and GT4? What are the differences between Huawei GT3 Pro and GT4? Dec 29, 2023 pm 02:27 PM

Many users will choose the Huawei brand when choosing smart watches. Among them, Huawei GT3pro and GT4 are very popular choices. Many users are curious about the difference between Huawei GT3pro and GT4. Let’s introduce the two to you. . What are the differences between Huawei GT3pro and GT4? 1. Appearance GT4: 46mm and 41mm, the material is glass mirror + stainless steel body + high-resolution fiber back shell. GT3pro: 46.6mm and 42.9mm, the material is sapphire glass + titanium body/ceramic body + ceramic back shell 2. Healthy GT4: Using the latest Huawei Truseen5.5+ algorithm, the results will be more accurate. GT3pro: Added ECG electrocardiogram and blood vessel and safety

How to implement drag-and-drop sorting and drag-and-drop operations in uniapp How to implement drag-and-drop sorting and drag-and-drop operations in uniapp Oct 19, 2023 am 09:39 AM

Uniapp is a cross-platform development framework. Its powerful cross-end capabilities allow developers to develop various applications quickly and easily. It is also very simple to implement drag-and-drop sorting and drag-and-drop operations in Uniapp, and it can support drag-and-drop operations of a variety of components and elements. This article will introduce how to use Uniapp to implement drag-and-drop sorting and drag-and-drop operations, and provide specific code examples. The drag-and-drop sorting function is very common in many applications. For example, it can be used to implement drag-and-drop sorting of lists, drag-and-drop sorting of icons, etc. Below we list

Explore the underlying principles and algorithm selection of the C++sort function Explore the underlying principles and algorithm selection of the C++sort function Apr 02, 2024 pm 05:36 PM

The bottom layer of the C++sort function uses merge sort, its complexity is O(nlogn), and provides different sorting algorithm choices, including quick sort, heap sort and stable sort.

Fix: Snipping tool not working in Windows 11 Fix: Snipping tool not working in Windows 11 Aug 24, 2023 am 09:48 AM

Why Snipping Tool Not Working on Windows 11 Understanding the root cause of the problem can help find the right solution. Here are the top reasons why the Snipping Tool might not be working properly: Focus Assistant is On: This prevents the Snipping Tool from opening. Corrupted application: If the snipping tool crashes on launch, it might be corrupted. Outdated graphics drivers: Incompatible drivers may interfere with the snipping tool. Interference from other applications: Other running applications may conflict with the Snipping Tool. Certificate has expired: An error during the upgrade process may cause this issu simple solution. These are suitable for most users and do not require any special technical knowledge. 1. Update Windows and Microsoft Store apps

Sort array using Array.Sort function in C# Sort array using Array.Sort function in C# Nov 18, 2023 am 10:37 AM

Title: Example of using the Array.Sort function to sort an array in C# Text: In C#, array is a commonly used data structure, and it is often necessary to sort the array. C# provides the Array class, which has the Sort method to conveniently sort arrays. This article will demonstrate how to use the Array.Sort function in C# to sort an array and provide specific code examples. First, we need to understand the basic usage of the Array.Sort function. Array.So

How to Fix Can't Connect to App Store Error on iPhone How to Fix Can't Connect to App Store Error on iPhone Jul 29, 2023 am 08:22 AM

Part 1: Initial Troubleshooting Steps Checking Apple’s System Status: Before delving into complex solutions, let’s start with the basics. The problem may not lie with your device; Apple's servers may be down. Visit Apple's System Status page to see if the AppStore is working properly. If there's a problem, all you can do is wait for Apple to fix it. Check your internet connection: Make sure you have a stable internet connection as the "Unable to connect to AppStore" issue can sometimes be attributed to a poor connection. Try switching between Wi-Fi and mobile data or resetting network settings (General > Reset > Reset Network Settings > Settings). Update your iOS version:

php提交表单通过后,弹出的对话框怎样在当前页弹出,该如何解决 php提交表单通过后,弹出的对话框怎样在当前页弹出,该如何解决 Jun 13, 2016 am 10:23 AM

php提交表单通过后,弹出的对话框怎样在当前页弹出php提交表单通过后,弹出的对话框怎样在当前页弹出而不是在空白页弹出?想实现这样的效果:而不是空白页弹出:------解决方案--------------------如果你的验证用PHP在后端,那么就用Ajax;仅供参考:HTML code

How to use the array_combine function in PHP to combine two arrays into an associative array How to use the array_combine function in PHP to combine two arrays into an associative array Jun 26, 2023 pm 01:41 PM

In PHP, there are many powerful array functions that can make array operations more convenient and faster. When we need to combine two arrays into an associative array, we can use PHP's array_combine function to achieve this operation. This function is actually used to combine the keys of one array as the values ​​of another array into a new associative array. Next, we will explain how to use the array_combine function in PHP to combine two arrays into an associative array. Learn about array_comb

See all articles