php sort()函数是一个用于对数组排序的常用方法。在应用程序设计中,它经常用于将数组中的元素按升序或降序排列。
$fruits = array("apple", "orange", "banana", "lemon"); sort($fruits); foreach($fruits as $key => $val) { echo "$key = $val\n"; }执行结果: 0 = apple 1 = banana 2 = lemon 3 = orange 在默认情况下,sort()函数会将数组的键(key)重置为从零开始的整数索引。 另外,sort()函数也可以对数字索引的关联数组进行排序。例如:
$age = array("John" => "25", "Bob" => "31", "Tom" => "28"); asort($age); foreach($age as $key => $val) { echo "$key = $val\n"; }执行结果: John = 25 Tom = 28 Bob = 31
$numbers = array(4, 1, 7, 3, 9, 2); sort($numbers, SORT_NUMERIC); foreach($numbers as $key => $val) { echo "$key = $val\n"; }执行结果: 0 = 1 1 = 2 2 = 3 3 = 4 4 = 7 5 = 9 如果需要对字符串进行不区分大小写的排序,则可以使用SORT_STRING和SORT_FLAG_CASE参数组合。例如:
$colors = array("Red", "blue", "Green", "YELLOW"); sort($colors, SORT_STRING | SORT_FLAG_CASE); foreach($colors as $key => $val) { echo "$key = $val\n"; }执行结果: 0 = blue 1 = Green 2 = Red 3 = YELLOW
$numbers = array(4, 1, 7, 3, 9, 2); sort($numbers, SORT_NUMERIC); $numbers = array_reverse($numbers); foreach($numbers as $key => $val) { echo "$key = $val\n"; }执行结果: 0 = 9 1 = 7 2 = 4 3 = 3 4 = 2 5 = 1
function my_sort($a, $b) { if($a == $b) return 0; return ($a < $b) ? -1 : 1; } $numbers = array(4, 1, 7, 3, 9, 2); usort($numbers, "my_sort"); foreach ($numbers as $key => $val) { echo "$key = $val\n"; }执行结果: 0 = 1 1 = 2 2 = 3 3 = 4 4 = 7 5 = 9 2. 对复杂数组进行排序 sort()函数可以对包括多维关联数组在内的复杂数组进行排序。例如:
$people = array( array("name" => "John", "age" => "30"), array("name" => "Bob", "age" => "25"), array("name" => "Tom", "age" => "28") ); function sortByName($a, $b) { return strcmp($a["name"], $b["name"]); } usort($people, "sortByName"); foreach ($people as $key => $val) { echo $val["name"] . ", " . $val["age"] . "\n"; }执行结果: Bob, 25 John, 30 Tom, 28
本文链接:http://task.lmcjl.com/news/1923.html