Home Backend Development PHP Tutorial Summary 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
php use function sort Way

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);
?>
Copy after login

The output result is as follows:

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

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);
?>
Copy after login

Its output is as follows:

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

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);
?>
Copy after login

Its output is as follows:

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

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);
?>
Copy after login

Its output is as follows:

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

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);
?>
Copy after login

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
)
Copy after login

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

Listing F

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

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

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

自然语言排序

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);
?>
Copy after login
Copy after login

它的输出结果如下:

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
)
Copy after login
Copy after login

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

自然语言能进行倒排吗?答案是肯定的!只要对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));
?>
Copy after login
Copy after login

下面是它的输出结果:

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

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

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;
}
}
?>
Copy after login
Copy after login

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

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

自然语言排序

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);
?>
Copy after login
Copy after login

它的输出结果如下:

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
)
Copy after login
Copy after login

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

自然语言能进行倒排吗?答案是肯定的!只要对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));
?>
Copy after login
Copy after login

下面是它的输出结果:

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

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

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;
}
}
?>
Copy after login
Copy after login

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

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

多维排序

最后,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);
?>
Copy after login

这里,我们在$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
)
)
Copy after login

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 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 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
1659
14
PHP Tutorial
1258
29
C# Tutorial
1232
24
How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

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: 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 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.

See all articles