search
HomeBackend DevelopmentPHP TutorialSummary of how to use various sorting functions in php
Summary of how to use various sorting functions in phpJun 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
php怎么把负数转为正整数php怎么把负数转为正整数Apr 19, 2022 pm 08:59 PM

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

php怎么实现几秒后执行一个函数php怎么实现几秒后执行一个函数Apr 24, 2022 pm 01:12 PM

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php怎么除以100保留两位小数php怎么除以100保留两位小数Apr 22, 2022 pm 06:23 PM

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

php怎么根据年月日判断是一年的第几天php怎么根据年月日判断是一年的第几天Apr 22, 2022 pm 05:02 PM

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

php怎么替换nbsp空格符php怎么替换nbsp空格符Apr 24, 2022 pm 02:55 PM

方法:1、用“str_replace("&nbsp;","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\&nbsp\;||\xc2\xa0)/","其他字符",$str)”语句。

php怎么判断有没有小数点php怎么判断有没有小数点Apr 20, 2022 pm 08:12 PM

php判断有没有小数点的方法:1、使用“strpos(数字字符串,'.')”语法,如果返回小数点在字符串中第一次出现的位置,则有小数点;2、使用“strrpos(数字字符串,'.')”语句,如果返回小数点在字符串中最后一次出现的位置,则有。

php怎么设置implode没有分隔符php怎么设置implode没有分隔符Apr 18, 2022 pm 05:39 PM

在PHP中,可以利用implode()函数的第一个参数来设置没有分隔符,该函数的第一个参数用于规定数组元素之间放置的内容,默认是空字符串,也可将第一个参数设置为空,语法为“implode(数组)”或者“implode("",数组)”。

php字符串有没有下标php字符串有没有下标Apr 24, 2022 am 11:49 AM

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

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)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!