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

  • 相关阅读:
    python学习之路01
    面向对象(2)__继承多态1
    面向对象(1)____私有公有 访问限制
    property
    yield理解
    列表推导式
    Django序列化1_基本的序列化和反序列化
    一些滑动操作
    装饰器
    django模板
  • 原文地址:https://www.cnblogs.com/hf8051/p/4660758.html
Copyright © 2011-2022 走看看