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正则表达式(regar expression)

php正则表达式(regar expression)

引言: 在编写处理字符串的程序或网页时,经常会有查找符合某些复杂规则的字符串 的需要。正则表达式就是用于描述这些规则的语法。 例:在判断用户邮件地址格式、手机号码格式或者采集别人网页内容...

解析PHP函数array_flip()在重复数组元素删除中的作用

我们都知道,PHP中的数组元素删除的方式可以有很多种,经常用到的函数有php中array_unique()。那么我们今天为大家介绍的PHP函数array_flip()在删除数组重复元素时...

php使用CURL伪造IP和来源实例详解

本文实例讲述了php使用CURL伪造IP和来源的方法。分享给大家供大家参考。具体分析如下: 伪造IP来源对于php来说是很简单的一件事情,我们只要利用了php的curl即可实现伪造IP来...

PHP防注入安全代码

简述:/*************************    说明:    判断传递的变量中是否含有非法字符 &...

PHP合并两个或多个数组的方法

PHP合并两个或多个数组的方法

使用运算符“+” PHP的数组运算符“+”可以用来联合两个(或多个数组)。 <?php header("content-type:text/html;charset=...