Sorting Array Values in PHP(数组排序)

yipeiwu_com6年前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中list方法用法示例

本文实例讲述了PHP中list方法用法。分享给大家供大家参考,具体如下: <?php function small_numbers() { return array...

PHP程序员编程注意事项

1.不转意html entities   一个基本的常识:所有不可信任的输入(特别是用户从form中提交的数据) ,输出之前都要转意。...

php中file_get_contents()函数用法实例

我们先来看一下php中的 file_get_contents()函数的语法 string file_get_contents(string $ filename,bool $ inc...

PHP操作路由器实现方法示例

本文实例讲述了PHP操作路由器实现方法。分享给大家供大家参考,具体如下: 用PHP操作路由器 我们经常会碰到需要自动换IP的需求,比方模拟点击投票,数据采集被封IP,Alexa作弊等等,...

PHP Session机制简介及用法

PHP Session机制简介及用法

当服务器创建了一个session(session_start()),服务器将会在服务器的指定文件夹下创建一个session文件,其名称为sessionID,并当做cookie的值发送给浏...