1. sort() - 对数组进行升序排序:
$numbers = [4, 2, 8, 1, 6];
sort($numbers);
print_r($numbers);
// 输出 Array ( [0] => 1 [1] => 2 [2] => 4 [3] => 6 [4] => 8 )
2. rsort() - 对数组进行降序排序:
$numbers = [4, 2, 8, 1, 6];
rsort($numbers);
print_r($numbers);
// 输出 Array ( [0] => 8 [1] => 6 [2] => 4 [3] => 2 [4] => 1 )
3. asort() - 根据值升序排序关联数组:
$ages = ["John" => 25, "Anna" => 30, "Bob" => 20];
asort($ages);
print_r($ages);
// 输出 Array ( [Bob] => 20 [John] => 25 [Anna] => 30 )
4. ksort() - 根据键升序排序关联数组:
$ages = ["John" => 25, "Anna" => 30, "Bob" => 20];
ksort($ages);
print_r($ages);
// 输出 Array ( [Anna] => 30 [Bob] => 20 [John] => 25 )
5. arsort() - 根据值降序排序关联数组:
$ages = ["John" => 25, "Anna" => 30, "Bob" => 20];
arsort($ages);
print_r($ages);
// 输出 Array ( [Anna] => 30 [John] => 25 [Bob] => 20 )
6. krsort() - 根据键降序排序关联数组:
$ages = ["John" => 25, "Anna" => 30, "Bob" => 20];
krsort($ages);
print_r($ages);
// 输出 Array ( [John] => 25 [Bob] => 20 [Anna] => 30 )
7. usort() - 使用用户自定义的比较函数对数组进行排序:
function customSort($a, $b) {
return $a["age"] - $b["age"];
}
$people = [
["name" => "John", "age" => 25],
["name" => "Anna", "age" => 30],
["name" => "Bob", "age" => 20]
];
usort($people, "customSort");
print_r($people);
// 输出 Array ( [2] => Array ( [name] => Bob [age] => 20 ) [0] => Array ( [name] => John [age] => 25 ) [1] => Array ( [name] => Anna [age] => 30 ) )
这只是PHP中一些常用的数组排序函数。根据需要,选择适当的排序函数,或者使用自定义排序函数来满足特定的需求。
转载请注明出处:http://www.zyzy.cn/article/detail/3403/PHP