search
HomeBackend DevelopmentPHP TutorialSummary of how to use various sorting functions in php

Summary of how to use various sorting functions in php

Jun 26, 2017 pm 01:17 PM
phpusefunctionsortWay

If you have been using PHP for a while, you should already be familiar with its arrays - this data structure allows you to store multiple values ​​in a single variable and use them as Operate on a collection.

Often, developers find it useful to sort values ​​or array elements using this data structure in PHP. PHP provides some sorting functions for a variety of arrays. These functions allow you to arrange elements within the array and also allow you to reorder them in many different ways. In this article we will discuss some of the most important functions in this sorting.

Simple sorting

First, let’s take a look at the simplest case: simply sorting an array element from low to high. This function can be used both numerically and The size arrangement can also be arranged alphabetically. PHP's sort() function implements this function, as shown in Listing A:

Listing A

<?php
$data = array(5,8,1,7,2);
sort($data);
print_r($data);
?>

The output result is as follows:

Array ([0] => 1
[1] => 2
[2] => 5
[3] => 7
[4] => 8
)

You can also use the rsort() function for sorting. Its result is opposite to the simple sorting result of sort() used previously. The Rsort() function sorts the array elements from high to low, either numerically or alphabetically. Listing B shows us an example of it:

Listing B

<?php 
$data = array(5,8,1,7,2);
rsort($data);
print_r($data);
?>

Its output is as follows:

Array ([0] => 8
[1] => 7
[2] => 5
[3] => 2
[4] => 1
)

Sort according to keywords

When we use arrays, we often reorder the array according to keywords, from high to low. The Ksort() function is a function that sorts according to keywords. At the same time, it maintains the relevance of keywords during the sorting process. Listing C is an example:

Listing C

<?php 
$data = array("US" => "United States", "IN" => "India", "DE" => "Germany", "ES" => "Spain");
ksort($data); 
print_r($data);
?>

Its output is as follows:

Array ([DE] => Germany
[ES] => Spain
[IN] => India
[US] => United States
)

The Krsort() function is based on The keyword inverts the array. Listing D is an example of this:

Listing D

<?php 
$data = array("US" => "United States", "IN" => "India", "DE" => "Germany", "ES" => "Spain");
krsort($data); 
print_r($data);
?>

Its output is as follows:

Array ([US] => United States
[IN] => India
[ES] => Spain
[DE] => Germany
)

Sort by value

If you want to use value sorting instead of keyword sorting, PHP can also meet your requirements. You just need to use the asort() function instead of the ksort() function mentioned earlier. As shown in Listing E:

Listing E

<?php 
$data = array("US" => "United States", "IN" => "India", "DE" => "Germany", "ES" => "Spain");
asort($data); 
print_r($data);
?>

The following is its output. Note the difference between this result and the result obtained using the ksort() function above - in both cases, the sorting is alphabetical, but they are sorted according to different fields of the array.

同时,请注意关键字-值之间的联系会始终保持;它只是关键字-值对排序后的一种方式,排序并不会改变它们的对应关系。

Array ([DE] => Germany
[IN] => India
[ES] => Spain
[US] => United States
)

现在,你肯定能猜到这种排序也可以进行倒排,它使用arsort()函数完成这个功能。Listing F就是一个例子:

Listing F

<?php 
$data = array("US" => "United States", "IN" => "India", "DE" => "Germany", "ES" => "Spain");
arsort($data); 
print_r($data);
?>

下面是它的输出结果,根据值按字母表顺序进行倒排。将下面的结果与用krsort()函数进行倒排后生成的结果进行比较,就能很容易明白两者的不同了。

Array ([US] => United States
[ES] => Spain
[IN] => India
[DE] => Germany
)

自然语言排序

PHP有一个非常独特的排序方式,这种方式使用认知而不是使用计算规则。这种特性称为自然语言排序,当创建模糊逻辑应用软件的时候这种排序方式非常有用。下面大家可以来看看它的一个简单例子,如Listing G所示:

Listing G

<?php 
$data = array("book-1", "book-10", "book-100", "book-5"); 
sort($data);
print_r($data);
natsort($data); 
print_r($data);
?>

它的输出结果如下:

Array ([0] => book-1
[1] => book-10
[2] => book-100
[3] => book-5
)
Array
(
[0] => book-1
[3] => book-5
[1] => book-10
[2] => book-100
)

它们的不同已经很清楚了:第二个排序结果更直观,更“人性化”,然而第一个则更符合算法规则,更具“计算机”特点。

自然语言能进行倒排吗?答案是肯定的!只要对natsort()的结果使用array_reverse()函数就可以了,Listing H就是一个简单例子:

Listing H

<?php 
$data = array("book-1", "book-10", "book-100", "book-5");
natsort($data); 
print_r(array_reverse($data));
?>

下面是它的输出结果:

Array ([0] => book-100
[1] => book-10
[2] => book-5
[3] => book-1
)

根据用户自定义的规则排序

PHP也能让你定义自己的排序算法,你可以通过创建你自己的比较函数,并把它传递给usort()函数。如果第一个参数比第二个参数“小”的话,比较函数必须返回一个比0小的数,如果第一参数比第二个参数“大”的话,比较函数应该返回一个比0大的数。

Listing I就是这样的一个例子,在这个例子中根据它们的长度对数组元素进行排序,最短的项放在最前面:

Listing I

<?php 
$data = array("joe@host.com", "john.doe@gh.co.uk", "asmithsonian@us.info", "jay@zoo.tw");
usort($data, &#39;sortByLen&#39;);
print_r($data); 
function sortByLen($a, $b) {
if (strlen($a) == strlen($b)) {
return 0;
} else {
return (strlen($a) > strlen($b)) ? 1 : -1;
}
}
?>

这样,就创建了我们自己的比较函数,这个函数使用strlen()函数比较每一个字符串的个数,然后分别返回1,0或-1.这个返回值是决定元素排列的基础。下面是它的输出结果:

Array ([0] => jay@zoo.tw
[1] => joe@host.com
[2] => john.doe@gh.co.uk
[3] => asmithsonian@us.info
)

自然语言排序

PHP有一个非常独特的排序方式,这种方式使用认知而不是使用计算规则。这种特性称为自然语言排序,当创建模糊逻辑应用软件的时候这种排序方式非常有用。下面大家可以来看看它的一个简单例子,如Listing G所示:

Listing G

<?php 
$data = array("book-1", "book-10", "book-100", "book-5"); 
sort($data);
print_r($data);
natsort($data); 
print_r($data);
?>

它的输出结果如下:

Array ([0] => book-1
[1] => book-10
[2] => book-100
[3] => book-5
)
Array
(
[0] => book-1
[3] => book-5
[1] => book-10
[2] => book-100
)

它们的不同已经很清楚了:第二个排序结果更直观,更“人性化”,然而第一个则更符合算法规则,更具“计算机”特点。

自然语言能进行倒排吗?答案是肯定的!只要对natsort()的结果使用array_reverse()函数就可以了,Listing H就是一个简单例子:

Listing H

<?php 
$data = array("book-1", "book-10", "book-100", "book-5");
natsort($data); 
print_r(array_reverse($data));
?>

下面是它的输出结果:

Array ([0] => book-100
[1] => book-10
[2] => book-5
[3] => book-1
)

根据用户自定义的规则排序

PHP也能让你定义自己的排序算法,你可以通过创建你自己的比较函数,并把它传递给usort()函数。如果第一个参数比第二个参数“小”的话,比较函数必须返回一个比0小的数,如果第一参数比第二个参数“大”的话,比较函数应该返回一个比0大的数。

Listing I就是这样的一个例子,在这个例子中根据它们的长度对数组元素进行排序,最短的项放在最前面:

Listing I

<?php 
$data = array("joe@host.com", "john.doe@gh.co.uk", "asmithsonian@us.info", "jay@zoo.tw");
usort($data, &#39;sortByLen&#39;);
print_r($data); 
function sortByLen($a, $b) {
if (strlen($a) == strlen($b)) {
return 0;
} else {
return (strlen($a) > strlen($b)) ? 1 : -1;
}
}
?>

这样,就创建了我们自己的比较函数,这个函数使用strlen()函数比较每一个字符串的个数,然后分别返回1,0或-1.这个返回值是决定元素排列的基础。下面是它的输出结果:

Array ([0] => jay@zoo.tw
[1] => joe@host.com
[2] => john.doe@gh.co.uk
[3] => asmithsonian@us.info
)

多维排序

最后,PHP也允许在多维数组上执行一些比较复杂的排序——例如,首先对一个嵌套数组使用一个普通的关键字进行排序,然后再根据另一个关键字进行排序。这与使用SQL的ORDER BY语句对多个字段进行排序非常相似。为了能更好的明白它是如何工作的,请仔细看Listing J所举的例子:

Listing J

<?php 
$data = array(array("id" => 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[&#39;name&#39;];
$rating[$key] = $value[&#39;rating&#39;];
}
array_multisort($rating, $name, $data); 
print_r($data);
?>

这里,我们在$data数组中模拟了一个行和列数组。然后,我使用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
)
)

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

这些例子应该让你对PHP中各种数组排序函数的使用有了初步的了解,也向你展示了一些隐藏在PHP数组处理工具包的内部功能。


The above is the detailed content of Summary of how to use various sorting functions in php. For more information, please follow other related articles on the PHP Chinese website!

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
What is the difference between unset() and session_destroy()?What is the difference between unset() and session_destroy()?May 04, 2025 am 12:19 AM

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

What is sticky sessions (session affinity) in the context of load balancing?What is sticky sessions (session affinity) in the context of load balancing?May 04, 2025 am 12:16 AM

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

What are the different session save handlers available in PHP?What are the different session save handlers available in PHP?May 04, 2025 am 12:14 AM

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

What is a session in PHP, and why are they used?What is a session in PHP, and why are they used?May 04, 2025 am 12:12 AM

Session in PHP is a mechanism for saving user data on the server side to maintain state between multiple requests. Specifically, 1) the session is started by the session_start() function, and data is stored and read through the $_SESSION super global array; 2) the session data is stored in the server's temporary files by default, but can be optimized through database or memory storage; 3) the session can be used to realize user login status tracking and shopping cart management functions; 4) Pay attention to the secure transmission and performance optimization of the session to ensure the security and efficiency of the application.

Explain the lifecycle of a PHP session.Explain the lifecycle of a PHP session.May 04, 2025 am 12:04 AM

PHPsessionsstartwithsession_start(),whichgeneratesauniqueIDandcreatesaserverfile;theypersistacrossrequestsandcanbemanuallyendedwithsession_destroy().1)Sessionsbeginwhensession_start()iscalled,creatingauniqueIDandserverfile.2)Theycontinueasdataisloade

What is the difference between absolute and idle session timeouts?What is the difference between absolute and idle session timeouts?May 03, 2025 am 12:21 AM

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

What steps would you take if sessions aren't working on your server?What steps would you take if sessions aren't working on your server?May 03, 2025 am 12:19 AM

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

What is the significance of the session_start() function?What is the significance of the session_start() function?May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

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 Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

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