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执行速率优化技巧小结

1.在可以用file_get_contents替代file、fopen、feof、fgets等系列方法的情况下,尽量用file_get_contents,因为他的效率高得多!但是要注意f...

php中如何判断一个网页请求是ajax请求还是普通请求

如何在php中判断一个网页请求是ajax请求还是普通请求?你可以通过传递参数的方法来实现,例如使用如下网址请求:/path/to/pkphp.com/script.php?ajax在ph...

PHP生成制作验证码的简单实例

PHP生成制作验证码的简单实例

看完就会,不会你打我,话不多说、开搞(人狠话不多) 1.0 首先先看代码 <?php header("Content-Type:text/html;Charset=UT...

PHP 与 UTF-8 的最佳实践详细介绍

《PHP中的字符串、编码、UTF-8》一文中描述了一些列的基础知识,比较枯燥,现在来说点有用的——PHP 字符串处理的最佳实践,本文是“PHP、字符串、编码、UTF-8”相关知识的第二部...

php Undefined index的问题

可以再错误语句前加上@ 也可以修改PHP.INI PHP.INI里的error_reporting = E_ALL造成的,如果不希望看到这个提示,可以 error_report...