代码改变世界

7.2.3、数组排序

2012-11-29 22:12  TONY|小四  阅读(181)  评论(0编辑  收藏  举报
  
 PHP Code By tony
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<?php
    
    /**
        数组的排序
     */

    
echo '数组的排序<br>';
    $fruit = 
array('banner','orange','apple');
    
// 没有使用排序是按下标进行排序的。
    print_r($fruit);
    
    
echo '<br>';
    
    
// 对中文也支持排序,还可以将数字按照升序排序
    sort($fruit);
    
    print_r($fruit);
    
echo '<br>';
    
    
/**
     * sort 可选参数的使用
     */

    
echo 'sort 可选参数的使用<br>';
    $numbers = 
array(2,12);
    
    print_r($numbers);
    
echo '<br>';
    
    sort($numbers,SORT_STRING);
    print_r($numbers);
    
echo '<br>';
    
    
/**
     * asort 对数组进行排序并保持索引关系
     */

    
echo 'asort 对数组进行排序并保持索引关系<br>';
    
    $fruit = 
array('banner','orange','apple');
    asort($fruit);  
// 原始下标多少,排序后下标保持不变
    print_r($fruit);
    
echo '<br>';
    
    
/**
     * ksort 对数组按照键名排序
     */

    $fruit = 
array('c'=>'banner','a'=>'orange','b'=>'apple');
    
    
// 按照键(key)来排序
    ksort($fruit);
    print_r($fruit);
    
echo '<br>';
    
    
/**
     * 反向排序(rsort、arsort、krsort),正向排序函数 sort、asort、ksort
     */

    
echo '反向排序';
    $numbers = 
array(3,24,2,5,7,2,5);
    rsort($numbers);
    print_r($numbers);
    
echo '<br>';
    
    
/**
     * 对数组进行反向排序,array 开头的函数,一般会创建一个新数组
     */

    
echo '对数组进行反向排序,array 开头的函数,一般会创建一个新数组<br>';
    $numbers = 
array(3,24,2,5,7,2,5);
    $a = array_reverse($numbers);
    print_r($a);
?>