Sorting Array Values in PHP(数组排序)

yipeiwu_com5年前PHP代码库
复制代码 代码如下:

$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中的Base62类(适用于数值转字符串)

Base62类源码:复制代码 代码如下:class Base62 {    private $string = "vPh7zZwA2LyU4bGq5tcVf...

PHP插件PHPMailer发送邮件功能

PHP插件PHPMailer发送邮件功能

本文实例为大家分享了ThinkPHP3.2.3发送邮件的具体代码,供大家参考,具体内容如下 首先第一步 :在网上down了一个PHPMailer插件,下载解压后,这里我们只需要用到其中两...

PHP函数rtrim()使用中的怪异现象分析

本文实例讲述了PHP函数rtrim()使用中的怪异现象。分享给大家供大家参考,具体如下: 今天用rtrim()函数时遇到了一个奇怪的问题: echo rtrim('<p>...

PHP中抽象类,接口功能、定义方法示例

本文实例讲述了PHP中抽象类,接口功能、定义方法。分享给大家供大家参考,具体如下: 这里先介绍接口,因为在我最近看的好几本php工具书中都没有提到抽象类。 本人也觉得,在理解了接口后抽象...

php 如何设置一个严格控制过期时间的session

1.php session 有效期 PHP的session有效期默认是1440秒(24分钟),如果客户端超过24分钟没有刷新,当前session会被回收,失效。 当用户关闭浏览器,会话结...