Home php教程 php手册 php数组排序之多维数组与一维数组

php数组排序之多维数组与一维数组

Jun 13, 2016 am 09:47 AM
php one under and multidimensional us sort array

我们知道在php数组中分为多维数组与一维数组,我们下面来分别讲述一下php多维数组与一维数组排序原理与实现方法吧。

一维数组

第一组 :sort 和 rsort ,按照PHP数组键值的顺序asc和逆序desc进行排序,同时破坏原来数组的索引关系——其实是删除索引之后重新建立从0开始的数字索引。看一下例程:

 代码如下 复制代码
  $a = array("a"=>1,2);
sort($a);
var_dump($a);
 
rsort($a);
var_dump($a);
?>
看一下第一个输出结果,第一个输出:
array(2) {
  [0]=>
  int(1)
  [1]=>
  int(2)
}
第二个输出:
array(2) {
  [0]=>
  int(5)
  [1]=>
  int(4)
}

发现没有我们原来定义的索引a哪里去了?哪里去了?可以肯定的说是被他们无情的删除了,你要是对原来的索引关系并不在意的话,可以使用他们!

第二组函数:asort 和 arsort ,这两个函数就比较厉害一点了,只要他们可以保留数组原有的索引关系,把上例的sort 和 rsort 分别用这两个函数替换一下,看运行结果:

 代码如下 复制代码
array(2) {
  ["a"]=>
  int(1)
  [0]=>
  int(2)
}
array(2) {
  [0]=>
  int(2)
  ["a"]=>
  int(1)
}

这个一看就明白的,不用说了吧!

第三组PHP数组排序函数:krsort 和 ksort 这两个不同于以上两组,这两函数是对键名进行排序的,大家可以把上例的函数替换成这两个,看看具体运行结果,这里也不说了,不然这个文章写的就太长了,怕有些兄弟没有耐心看到本文的重点,虽然重点就在下边!

通过自定义函数对PHP数组进行排序,有三个函数分别是:
uasort 通过自定义函数对PHP数组的键值进行排序,并且保留原来的索引关系。
uksort 通过自定义函数对PHP数组的键名进行排序,并且保留原来的索引关系。
usort通过自定义函数对PHP数组的键值进行排序,并且删除原来的索引关系,从零开始建立新的索引。

这个地方当然需要一个例子:

 代码如下 复制代码
 
输出结果:
array(4) {
  [0]=>
  int(1)
  [3]=>
  int(5)
  [1]=>
  int(4)
  [2]=>
  int(3)
}

多维数组的排序


例如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 – 将项目按照字符串比较

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

Video Face Swap

Video Face Swap

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

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
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)

Hot Topics

Java Tutorial
1670
14
PHP Tutorial
1274
29
C# Tutorial
1256
24
PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 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

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 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.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 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.

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 and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 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 and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP: Handling Databases and Server-Side Logic PHP: Handling Databases and Server-Side Logic Apr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

See all articles