年年有"余"

 找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 1738|回复: 0

PHP排序最为常用的几个函数sort&ksort&asort

[复制链接]
  • TA的每日心情

    2024-10-15 10:05
  • 签到天数: 372 天

    [LV.9]以坛为家II

    发表于 2015-12-30 17:48:34 | 显示全部楼层 |阅读模式
    本帖最后由 Sian 于 2015-12-30 17:51 编辑

    [PHP] 纯文本查看 复制代码
    <?php
            
            /*
             *        sort() & rsort()
             */
    
            $array = array(1,4,52,2,6,9,12,54,3,"a", "c", "b", "aa", "ac", "ab", "赵", "钱", "孙");
            // 按字母或数字排序,如果是字符串,按字符串从左到右优先级比较,即aa<ab
            // 并且将所有下标都去掉,只关心值的绝对位置
            // 不支持中文排序,排序后改变原数组的顺序
            print_r($array);
            echo "<br/>";
            sort($array);
            print_r($array);
            echo "<br/>";
            rsort($array);
            print_r($array);
    
            
            /*
             *        ksort() & krsort()
             */
            // 按键排序
            $array = array("1"=>"one", "3"=>"three", "2"=>"two");
            print_r($array);
            echo "<br/>";
            ksort($array);
            print_r($array);
            echo "<br/>";
            krsort($array);
            print_r($array);
            echo "<br/>";
            
            /*
             *        asort() & arsort()
             */
            // 按值排序
            $array = array("one"=>"1", "three"=>"3", "two"=>"2");
            print_r($array);
            echo "<br/>";
            asort($array);
            print_r($array);
            echo "<br/>";
            arsort($array);
            print_r($array);
            echo "<br/>";
            

    输出结果一:
    Array ( [0] => 1 [1] => 4 [2] => 3 [3] => a [4] => c [5] => b [6] => aa [7] => ac [8] => ab [9] => 赵 [10] => 钱 [11] => 孙 )
    Array ( [0] => a [1] => aa [2] => ab [3] => ac [4] => b [5] => c [6] => 孙 [7] => 赵 [8] => 钱 [9] => 1 [10] => 3 [11] => 4 )
    Array ( [0] => 4 [1] => 3 [2] => 1 [3] => 钱 [4] => 赵 [5] => 孙 [6] => c [7] => b [8] => ac [9] => ab [10] => aa [11] => a )
    输出结果二:
    Array ( [1] => one [3] => three [2] => two )
    Array ( [1] => one [2] => two [3] => three )
    Array ( [3] => three [2] => two [1] => one )
    输出结果三:
    Array ( [one] => 1 [three] => 3 [two] => 2 )
    Array ( [one] => 1 [two] => 2 [three] => 3 )
    Array ( [three] => 3 [two] => 2 [one] => 1 )
    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    手机版|小黑屋|Archiver|iOS开发笔记 ( 湘ICP备14010846号 )

    GMT+8, 2024-12-22 17:54 , Processed in 0.043674 second(s), 18 queries .

    Powered by Discuz! X3.4

    Copyright © 2001-2021, Tencent Cloud.

    快速回复 返回顶部 返回列表