php数组排序的方法有哪几种

PhpPhp 2023-08-28 22:43:37 1077
摘要: php数组排序的方法常见方法有6种:1、sort()-对数组按升序排序$numbers=array(4,2,8,6);sort($numbers);print_r($numbers);//Output:Array([0]=>2[1]=>4[2]=>6[3]=>8)2、rsort()-对数组按...

php数组排序的方法常见方法有6种:

1、sort() - 对数组按升序排序

$numbers = array(4, 2, 8, 6);
sort($numbers);
print_r($numbers); // Output: Array ( [0] => 2 [1] => 4 [2] => 6 [3] => 8 )

2、rsort() - 对数组按降序排序

$numbers = array(4, 2, 8, 6);
rsort($numbers);
print_r($numbers); // Output: Array ( [0] => 8 [1] => 6 [2] => 4 [3] => 2 )

3、asort() - 根据值排序,并保留索引关系

$age = array("Peter" => "35", "Ben" => "37", "Joe" => "43");
asort($age);
print_r($age); // Output: Array ( [Peter] => 35 [Ben] => 37 [Joe] => 43 )

4、ksort() - 根据键排序,保留索引关系

$age = array("Peter" => "35", "Ben" => "37", "Joe" => "43");
ksort($age);
print_r($age); // Output: Array ( [Ben] => 37 [Joe] => 43 [Peter] => 35 )

5、arsort()-根据值降序排序,并保留索引关系

$age = array("Peter" => "35", "Ben" => "37", "Joe" => "43");
arsort($age);
print_r($age); // Output: Array ( [Joe] => 43 [Ben] => 37 [Peter] => 35 )

6、krsort() - 根据键降序排序,保留索引关系

$age = array("Peter" => "35", "Ben" => "37", "Joe" => "43");
krsort($age);
print_r($age); // Output: Array ( [Peter] => 35 [Joe] => 43 [