PHP development basic tutorial: Sorting of arrays
In this chapter, we will introduce the following PHP array sorting functions one by one:
sort() - Sort the array in ascending order Arrange
rsort() - Sort the array in descending order
asort() - Sort the array in ascending order based on the value of the associative array
ksort() - Sort the array in ascending order according to the keys of the associative array
arsort() - Sort the array according to the value of the associative array Sort in descending order
krsort() - Sort the array in descending order according to the key of the associative array
1. sort() - Sort the array in ascending order
The following example sorts the elements in the $fruits array according to Arrange alphabetically in ascending order:
<?php
$fruits = array("lemon", "orange", "banana", "apple");
sort($fruits);
foreach ($fruits as $key => $val) {
echo "fruits[" . $key . "] = " . $val . "<br/>";
}
?>## 2. rsort() - Sort the array in descending order
<?php
$fruits = array("lemon", "orange", "banana", "apple");
rsort($fruits);
foreach ($fruits as $key => $val) {
echo "fruits[" . $key . "] = " . $val . "<br/>";
}
?>3. asort() - Arrange the array in ascending order according to the value of the associative array
4. ksort() - According to the key of the associative array , sort the array in ascending order
##5. arsort() - Sort the array in descending order based on the value of the associative array
6. krsort() - Sort the array in descending order according to the key of the associated arrayComprehensive example: The code is as follows
<?php
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
//asort() - 根据关联数组的值,对数组进行升序排列
echo "<h3>asort() - 根据关联数组的值,对数组进行升序排列</h3>";
asort($fruits);
foreach ($fruits as $key => $val) {
echo "$key = $val<br/>";
}
echo "<hr/>";
//ksort() - 根据关联数组的键,对数组进行升序排列
echo "<h3>ksort() - 根据关联数组的键,对数组进行升序排列</h3>";
ksort($fruits);
foreach ($fruits as $key => $val) {
echo "$key = $val<br/>";
}
echo "<hr/>";
//arsort() - 根据关联数组的值,对数组进行降序排列
echo "<h3>arsort() - 根据关联数组的值,对数组进行降序排列</h3>";
arsort($fruits);
foreach ($fruits as $key => $val) {
echo "$key = $val<br/>";
}
echo "<hr/>";
//krsort() - 根据关联数组的键,对数组进行降序排列
echo "<h3>krsort() - 根据关联数组的键,对数组进行降序排列</h3>";
krsort($fruits);
foreach ($fruits as $key => $val) {
echo "$key = $val<br/>";
}
echo "<hr/>";
?>Note: Each sorting function also has some optional parameters. You can refer to the PHP manual

