Sorting Array Values in PHP(数组排序)

 更新时间:2011年09月15日 21:43:14   作者:  
有时候,你可能需要对数组内的值进行排序,那么就可以参考下面的文章。
复制代码 代码如下:

$full_name = array();
$full_name["Roger"] = "Waters";
$full_name["Richard"] = "Wright";
$full_name["Nick"] = "Mason";
$full_name["David"] = "Gilmour";

To sort this array, you just use the assort( ) function. This involves nothing more complex than typing the word asort, followed by round brackets. In between the round brackets, type in the name of your Associative array:
复制代码 代码如下:

asort($full_name);

The letter "a" tells PHP that the array is an Associative one. (If you don't have the "a" before "sort", your key names will turn in to numbers!). The "a" also tells PHP to sort by the Value, and NOT by the key. In our script above, the surnames will be sorted. If you want to sort using the Key, then you can use ksort() instead.

If you have a Scalar array (numbers as Keys), then you leave the "a" off. Like this:
复制代码 代码如下:

$numbers = array( );
$numbers[]="2";
$numbers[]="8";
$numbers[]="10";
$numbers[]="6";
sort($numbers);
print $numbers[0] ;
print $numbers[1];
print $numbers[2] ;
print $numbers[3];

The numbers are then sorted from lowest to highest. If you want to sort in reverse order then you need the following:

rsort( ) – Sorts a Scalar array in reverse order
arsort( ) - Sorts the Values in an Associative array in reverse order
krsort( ) - Sorts the Keys in an Associative array in reverse order

In the next part, we look at how to get a random value from an array.

相关文章

  • PHP输出缓存ob系列函数详解

    PHP输出缓存ob系列函数详解

    ob,输出缓冲区,是output buffering的简称,而不是output cache。ob用对了,是能对速度有一定的帮助,但是盲目的加上ob函数,只会增加CPU额外的负担
    2014-03-03
  • php中cookie实现二级域名可访问操作的方法

    php中cookie实现二级域名可访问操作的方法

    这篇文章主要介绍了php中cookie实现二级域名可访问操作的方法,对比了常用的setcookie函数用法,并给出了一个设置cookie的类文件来实现这一功能,是非常实用的技巧,需要的朋友可以参考下
    2014-11-11
  • PHP小技巧之函数重载

    PHP小技巧之函数重载

    php 作为一种弱类型语言,本身不能像强类型如java ,c++那样,直接的实现重载。不过可以通过一些方法,间接的实现重载。
    2014-06-06
  • PHP文件上传利用的常见函数总结大全

    PHP文件上传利用的常见函数总结大全

    文件上传是开发中常见的一个功能,下面这篇文章主要给大家介绍了关于PHP文件上传利用的常见函数,文中通过实例代码介绍的非常详细,需要的朋友可以参考下
    2022-03-03
  • PHP pthread拓展使用和注意点

    PHP pthread拓展使用和注意点

    这篇文章主要介绍了PHP pthread拓展使用和注意点,对此有需要的朋友们可以参考阅读下。
    2020-01-01
  • php+xml实现在线英文词典之添加词条的方法

    php+xml实现在线英文词典之添加词条的方法

    这篇文章主要介绍了php+xml实现在线英文词典之添加词条的方法,接着上一篇的通过英文查询汉字进一步完善了词条的添加功能,具有一定参考借鉴价值,需要的朋友可以参考下
    2015-01-01
  • PHP文件上传类实例详解

    PHP文件上传类实例详解

    这篇文章主要介绍了PHP文件上传类,结合实例形式详细分析了PHP上传文件类的实现代码与相关使用技巧,需要的朋友可以参考下
    2016-04-04
  • PHP如何获取Cookie并实现模拟登录

    PHP如何获取Cookie并实现模拟登录

    这篇文章主要介绍了PHP如何获取Cookie并实现模拟登录,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-07-07
  • php 启动报错如何解决

    php 启动报错如何解决

    php 启动时报错的情况,想必很多朋友都有遇到过吧,下面是具体的解决方法
    2014-01-01
  • php和C#的yield迭代器实现方法对比分析

    php和C#的yield迭代器实现方法对比分析

    这篇文章主要介绍了php和C#的yield迭代器实现方法,简单说明了yield迭代器的原理,并结合具体实例形式对比分析了php和C#的yield迭代器相关使用技巧,需要的朋友可以参考下
    2019-07-07

最新评论