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读取XML值的代码(推荐)

用Php读取XML最简单的情况: XML文件(cy.xml)如下: 复制代码 代码如下: <?xml version=”1.0″ encoding=”gb2312″?> &l...

thinkphp3.0 模板中函数的使用

变量的来源: 1 从php分配的变量,使用assign分配 2 系统变量 3 路径替换变量 不能使用函数的变量 变量输出快捷标签 {@var}//输出Session变量 和{$Think...

php5编程中的异常处理详细方法介绍

1 首先是try,catch  <?php  $path = "D:\\\\in.txt";  try //检...

php数组函数序列之krsort()- 对数组的元素键名进行降序排序,保持索引关系

krsort()定义和用法 krsort() 函数将数组按照键逆向排序,为数组值保留原来的键。 可选的第二个参数包含附加的排序标志。 若成功,则返回 TRUE,否则返回 FALSE。 语...

PHP多线程类及用法实例

本文实例讲述了PHP多线程类及用法。分享给大家供大家参考。具体分析如下: 一般来说可通过WEB服务器来实现PHP多线程功能,当然,对多线程有深入理解的人都知道通过WEB服务器实现的多线程...