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读取XML文件的方法实例总结【DOMDocument及simplexml方法】

本文实例讲述了PHP读取XML文件的方法。分享给大家供大家参考,具体如下: 使用DOMDocument对象读取xml 创建一个DOMDocument对象 $doc = new DOM...

php使用环形链表解决约瑟夫问题完整示例

本文实例讲述了php使用环形链表解决约瑟夫问题。分享给大家供大家参考,具体如下: 约瑟夫问题: Josephu问题为:设编号为1,2,...n的n个人围坐一圈,约定编号为k(1<=...

Zend Studio (eclipse)使用速度优化方法

原文标题是优化 myeclipse7.0 速度(尤其是building workspace),都是eclipse设置一样的。 大家一定对buileding workspace时那缓慢的速...

解析如何通过PHP函数获取当前运行的环境 来进行判断执行逻辑(小技巧)

一般情况下,我们的运行环境是 apache,当然也有些人是用IIS环境的 我们要是想知道我们目前运行的环境是什么的话,那我们只需要用函数php_sapi_name()来测试 进行比较判断...

dede全站URL静态化改造[070414更正]

1、将include复制到网站中的include目录。 2、修改数据库 将所有文档设置为“仅动态”,可以进入数据库管理中,执行下面命令: update dede_archive...