PHP提供了几种方法来对数组的键值进行排序。以下是一些常用的方法:
$fruits = array("apple", "banana", "cherry");
sort($fruits);
$fruits = array("apple", "banana", "cherry");
rsort($fruits);
$fruits = array("a" => "apple", "b" => "banana", "c" => "cherry");
asort($fruits);
$fruits = array("a" => "apple", "b" => "banana", "c" => "cherry");
arsort($fruits);
$fruits = array("c" => "cherry", "b" => "banana", "a" => "apple");
ksort($fruits);
$fruits = array("c" => "cherry", "b" => "banana", "a" => "apple");
krsort($fruits);
这些排序函数会改变原始数组的顺序。如果要保留原始数组的顺序,可以使用以下函数:
$fruits = array("a" => "apple", "b" => "banana", "c" => "cherry");
uasort($fruits, function($a, $b) {
return strcmp($a, $b);
});
$fruits = array("a" => "apple", "b" => "banana", "c" => "cherry");
uasort($fruits, function($a, $b) {
return strcmp($a, $b);
});
这些方法中的uasort()和uksort()函数允许使用自定义的比较函数进行排序,以实现更复杂的排序逻辑。