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+js实现百度地图多点标注的方法

php+js实现百度地图多点标注的方法

本文实例讲述了php+js实现百度地图多点标注的方法。分享给大家供大家参考,具体如下: 1.php创建json数据 $products = $this->product_db...

PHP5.5迭代生成器用法实例详解

本文实例讲述了PHP5.5迭代生成器用法。分享给大家供大家参考,具体如下: PHP5.5引入了迭代生成器的概念,迭代的概念早就在PHP有了,但是迭代生成器是PHP的一个新特性,这跟pyt...

php expects parameter 1 to be resource, array given 错误

如果你使用的是封装好的类 例如 function fetch_array($query, $result_type = MYSQL_ASSOC) { return mysql_fetch...

PHP 抓取网页图片并且另存为的实现代码

下面是源代码,及其相关解释 复制代码 代码如下: <?php //URL是远程的完整图片地址,不能为空, $filename 是另存为的图片名字 //默认把图片放在以此脚本相同的目...

9条PHP编程小知识及易犯的小错误

变量声明 如果在一条语句中声明一个变量,如下所示:$var='value';编译器首先会求出语句右半部分的值,恰恰正是语句的这一部分常常会引发错误。如果使用的语法不正确,就会出现解析错误...