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中几种常见安全设置详解

另外,目前闹的轰轰烈烈的SQL Injection也是在PHP上有很多利用方式,所以要保证安全,PHP代码编写是一方面,PHP的配置更是非常关键。 我们php手手工安装的,php的默认...

Yii框架调试心得--在页面输出执行sql语句

Yii框架调试心得--在页面输出执行sql语句

我们使用:yiidebugtb来调试(因为用他界面比较美观,不影响界面其他元素)。 1.下载yiidebugtb,并且放入到 application.extensions.yiidebu...

php设计模式 Builder(建造者模式)

复制代码 代码如下: <?php /** * 建造者模式 * * 将一个复杂对象的构建与它的表示分离,使用同样的构建过程可以创建不同的表示 */ class Product { p...

PHP中使用数组指针函数操作数组示例

数组的内部指针是数组内部的组织机制,指向一个数组中的某个元素。默认是指向数组中第一个元素通过移动或改变指针的位置,可以访问数组中的任意元素。对于数组指针的控制PHP提供了以下几个内建函数...

微信公众平台之快递查询功能用法实例

本文实例讲述了微信公众平台之快递查询功能用法。分享给大家供大家参考。具体如下: 使用方法: #查快递(或三个首字母ckd)#快递编号#快递单号 如(查询EMS单号为10346164940...