zoukankan      html  css  js  c++  java
  • php -- 数组排序

    PHP 数组排序函数:

      sort() - 对数组进行升序排列

      rsort() - 对数组进行降序排列

      asort() - 根据关联数组的值,对数组进行升序排列

      ksort() - 根据关联数组的键,对数组进行升序排列

      arsort() - 根据关联数组的值,对数组进行降序排列

      krsort() - 根据关联数组的键,对数组进行降序排列

    这些函数都是直接对原有数组进行操作,直接修改数组

    sort() - 对数组进行升序排列

    1、将 $cars 数组中的元素按照字母升序排列: 

    <?php
    $cars=array("Volvo","BMW","Toyota");
    sort($cars);
    ?>

    结果:

    BMW
    Toyota
    Volvo

    2、将 $numbers 数组中的元素按照数字升序排列

    <?php
    $numbers=array(4,6,2,22,11);
    sort($numbers);
    ?>

    结果:

    2
    4
    6
    11
    22

    rsort() - 对数组进行降序排列

    与sort()刚好相反

    1、将 $cars 数组中的元素按照字母降序排列

    2、将 $numbers 数组中的元素按照数字降序排列

    ksort() - 根据数组的键,对数组进行升序排列

    根据数组的键,对关联数组进行升序排列

    <?php
    $age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
    ksort($age);
    ?>

    结果:

    Key=Ben, Value=37
    Key=Joe, Value=43
    Key=Peter, Value=35

    先B 再J 再P

    krsort() - 根据数组的键,对数组进行降序排列

    根据数组的键,对关联数组进行降序排列

    <?php
    $age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
    krsort($age);
    ?>

    结果:

    Key=Peter, Value=35
    Key=Joe, Value=43
    Key=Ben, Value=37

    asort() - 根据数组的值,对数组进行升序排列

    根据数组的值,对关联数组进行升序排列

    <?php
    $age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
    asort($age);
    ?>

    结果:

    Key=Peter, Value=35
    Key=Ben, Value=37
    Key=Joe, Value=43

    arsort() - 根据数组的值,对数组进行降序排列

    根据数组的值,对关联数组进行降序排列

    <?php
    $age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
    arsort($age);
    ?>

    结果:

    Key=Joe, Value=43
    Key=Ben, Value=37
    Key=Peter, Value=35

  • 相关阅读:
    Linux中大括号{}的应用
    shell script编程(1)>>学生成绩管理系统
    不同版本的Linux防火墙关闭和开启
    shell script的执行方式区别
    包管理介绍(DPKG,APT,RPM,YUM,DNF)
    MBR与GPT,BIOS与UEFI..总结
    Windows10下安装Ubuntu的错误总结
    学生管理系统及票务管理系统总结
    python 3.x和python 2.x下的换行问题
    输出整数各位数字
  • 原文地址:https://www.cnblogs.com/hf8051/p/4660758.html
Copyright © 2011-2022 走看看