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中长文章分页显示实现代码

欢迎交流!实现代码如下: 复制代码 代码如下: <?php include('include/config.php'); ?> <?php /** *Author:乌鸟...

PHP读取文件并可支持远程文件的代码分享

php读取文件 案例一 复制代码 代码如下: <?php $file = 'jb51.net.php'; //本案例不支持远程 $fso = fopen($file, 'r');...

php通过执行CutyCapt命令实现网页截图的方法

本文实例讲述了php通过执行CutyCapt命令实现网页截图的方法。分享给大家供大家参考,具体如下: 用php使用exec执行命令 PS.默认情况下exec函数是禁用的,打开php.in...

PHP 程序员应该使用的10个组件

开源解决方案可以给你很大的帮助,比如: 开源代码是由很多人一起完成的,因此往往比一个人完成的结果要好。 你可以获得免费的代码更新和升级,否则你需要自己来写这些新的内容。 你节省了开...

在PHP中实现Javascript的escape()函数代码

这里,一般都需要预先将正常的字符串编码成 JavaScript unescape() 函数能够解译的格式,以 PHP 为例,可以使用以下函数实现 Javascript 中 escape(...