大家知道,数组排序最常用的函数就是 sort($arr); 它的作用是按数组的键值升序排列,并且排序后的数组键名不再是原来的键名,是按新数组来重新设置的键名,而有时我们要求更复杂的排序,如按键名排序,这里用到 ksort($arr); 函数,它会根据数组的键名排序,并维持原有的键值关系,相对应的 asort($arr); 函数,是按键值排序,且维持原有的键值关系,同样原理,rsort(); arsort(); krsort(); 函数除了排序是按降序排列外,其它与sort(); rsort(); ksort(); 相同,数组操作是PHP很重要的基础,希望能好好运用,一维数组例子.
实例代码如下:
- function my_sort($a, $b)
- {
- if ($a == $b) return 0;
- return ($a > $b) ? -1 : 1;
- }
- $people = array("Swanson" => "Joe",
- "Griffin" => "Peter", "Quagmire" => "Glenn",
- "swanson" => "joe", "griffin" => "peter",
- "quagmire" => "glenn");
- uksort($people, "my_sort");
- print_r ($people);
- ?>
输出:
- Array
- (
- [swanson] => joe
- [quagmire] => glenn
- [griffin] => peter
- [Swanson] => Joe
- [Quagmire] => Glenn
- [Griffin] => Peter
- )
如下面这个二维数组,需要按照sort键名来排序,那么array_multisort() 就无法直接实现了:
实例代码如下:
- $data[5] = array('volume' => 67, 'edition' => 2);
- $data[4] = array('volume' => 86, 'edition' => 1);
- $data[2] = array('volume' => 85, 'edition' => 6);
- $data[3] = array('volume' => 98, 'edition' => 2);
- $data[1] = array('volume' => 86, 'edition' => 6);
- $data[6] = array('volume' => 67, 'edition' => 7);
-
- foreach ($data as $k => $v) {
- $edition[] = $v['edition'];
- }
- array_multisort($edition, SORT_ASC, $data);
- print_r($data);将输出:
- Array
- (
- [0] => Array
- (
- [volume] => 86
- [edition] => 1
- )
- [1] => Array
- (
- [volume] => 67
- [edition] => 2
- )
- [2] => Array
- (
- [volume] => 98
- [edition] => 2
- )
- [3] => Array
- (
- [volume] => 85
- [edition] => 6
- )
- [4] => Array
- (
- [volume] => 86
- [edition] => 6
- )
- [5] => Array
- (
- [volume] => 67
- [edition] => 7
- )
- )
•sort() 函数用于对数组单元从低到高进行排序,
•rsort() 函数用于对数组单元从高到低进行排序,
•asort() 函数用于对数组单元从低到高进行排序并保持索引关系,
•arsort() 函数用于对数组单元从高到低进行排序并保持索引关系,
•ksort() 函数用于对数组单元按照键名从低到高进行排序,
•krsort() 函数用于对数组单元按照键名从高到低进行排序.