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中声明数组的方式主要有两种:一是应用array()...

php基于闭包实现函数的自调用(递归)实例分析

本文实例讲述了php基于闭包实现函数的自调用(递归)的方法。分享给大家供大家参考,具体如下: php的闭包可能不常用,但是在某些场合之下还是可以考虑用php的闭包来实现某些功能的,比如递...

php生成图片验证码的方法

php生成图片验证码的方法

本文为大家分享了php生成图片验证码的方法,供大家参考,具体内容如下 首先从指定字符集合中随机抽取固定数目的字符,以一种不规则的方法画在画布上,再适当添加一些干扰点和干扰元素,最后将图片...

php+js实现百度地图多点标注的方法

php+js实现百度地图多点标注的方法

本文实例讲述了php+js实现百度地图多点标注的方法。分享给大家供大家参考,具体如下: 1.php创建json数据 $products = $this->product_db...

PHP中使用jQuery+Ajax实现分页查询多功能操作(示例讲解)

PHP中使用jQuery+Ajax实现分页查询多功能操作(示例讲解)

1.首先做主页面Ajax_pag.php 代码如下: <!DOCTYPE html> <html> <head> <meta c...