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 ADODB生成HTML表格函数rs2html功能【附错误处理函数用法】

PHP ADODB生成HTML表格函数rs2html功能【附错误处理函数用法】

本文实例讲述了PHP ADODB生成HTML表格函数rs2html功能。分享给大家供大家参考,具体如下: 一、代码 adodb.inc.php可从官方网站http://adodb.sou...

PHP文件上传类实例详解

本文实例讲述了PHP文件上传类。分享给大家供大家参考,具体如下: 这里演示了FileUpload.class.php文件上传类,其中用到了两个常量,可在网站配置文件中定义: defi...

php实现QQ空间获取当前用户的用户名并生成图片

本文实例讲述了php实现QQ空间获取当前用户的用户名并生成图片的方法。分享给大家供大家参考。具体如下: 最近发现空间里经常会转载一些含有当前用户昵称和qq号的图片,很好奇,研究了一下原理...

PHP读取Excel类文件

PHP读取Excel类文件

想要使用PHP读取Excel文件必然要用到PHPExcel开源类库,网上资源应该挺多的。但是每一种的操作必然都是不同的,可原理应该都是大同小异。 这个文件夹里包含的就是PHPExcel类...

php post大量数据时发现数据丢失问题解决方法

php post大量数据时发现数据丢失问题解决方法

解决办法: 在php.ini中将max_input_vars调大改为5000就可以了 原因追查: from的enctype="multipart/form-data" php版本5.6....