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验证手机号码(支持归属地查询及编码为UTF8)

复制代码 代码如下: <?php // 手机号验证 function checkMobileValidity($mobilephone){ $exp = "/^13[0-9]{1}...

PHP $_FILES函数详解

如: 复制代码 代码如下: <form enctype="multipart/form-data" action="upload.php" method="post"> &l...

C# Assembly类访问程序集信息

C#中通过Assembly类可以访问程序集信息. 1.允许访问给定程序集的元元素,包含可以加载和执行程序集的方法; 2.加载程序集:使用静态方法Assembly.Load(程序集名称)或...

php 大数据量及海量数据处理算法总结

下面的方法是我对海量数据的处理方法进行了一个一般性的总结,当然这些方法可能并不能完全覆盖所有的问题,但是这样的一些方法也基本可以处理绝大多数遇到的问题。下面的一些问题基本直接来源于公司的...

使用php 获取时间今天明天昨天时间戳的详解

使用php获取时间今天明天昨天时间戳2013-06-20 11:12<?phpecho "今天:".date("Y-m-d")."<br>";  &...