Home >Backend Development >PHP Tutorial >Master the correct posture for sorting arrays in PHP

Master the correct posture for sorting arrays in PHP

autoload
autoloadOriginal
2021-04-25 12:01:055033browse

Arrays are a more commonly used data type in PHP. How to sort the data in the array to facilitate data management. This article will take you to see how to sort the array using PHP's built-in functions.

1. Sort the array according to the array key value

<?php
$arr1 = array(3,1,5,2,0);
sort($arr1);
print_r($arr1);
echo "<br>";

$arr2 = array(3,1,5,2,0);
rsort($arr2);
print_r($arr2);
?>
输出:Array ( [0] => 0 [1] => 1 [2] => 2 [3] => 3 [4] => 5 )
      Array ( [0] => 5 [1] => 3 [2] => 2 [3] => 1 [4] => 0 )

sort() - Sort the array Sort in ascending order; rsort() - Sort the array in descending order

2. Sort the array according to the associative array key value

<?php
$fruits1 = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
arsort($fruits1);
foreach ($fruits1 as $key => $val) {
    echo "$key = $val;";
}
echo "<br>";
$fruits2 = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
asort($fruits2);
foreach ($fruits2 as $key => $val) {
    echo "$key = $val\n";
}
?>
输出:a = orange;d = lemon;b = banana;c = apple;
      c = apple b = banana d = lemon a = orange

arsort() - Sort the array in descending order according to the value of the associative array; asort() - Sort the array in ascending order according to the value of the associative array

3. Sort the array according to the key of the associative array

<?php
$fruits1 = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
krsort($fruits1);
foreach ($fruits1 as $key => $val) {
    echo "$key = $val\n";
}
echo "<br>";

$fruits2 = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
ksort($fruits2);
foreach ($fruits2 as $key => $val) {
    echo "$key = $val\n";
}
?>
输出:d = lemon c = apple b = banana a = orange
      a = orange b = banana c = apple d = lemon

krsort() - Sort the array according to the key of the associative array Sort in descending order;ksort() - Sort the array in ascending order according to the key of the associated array

Recommendation:2021 Summary of PHP interview questions (collection)》《php video tutorial

The above is the detailed content of Master the correct posture for sorting arrays 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