Sorting Array Values in PHP(数组排序)

yipeiwu_com5年前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中记录用户访问过的产品,在cookie记录产品id,id取得产品信息

1.测试方法www.xxx.com/test.php?content_id=自己定义,如:44 复制代码 代码如下: $content_id = array();//1.创建一个数组 $...

PHP实现二叉树的深度优先与广度优先遍历方法

本文实例讲述了PHP实现二叉树的深度优先与广度优先遍历方法。分享给大家供大家参考。具体如下: #二叉树的广度优先遍历 #使用一个队列实现 class Node { public $...

php实现汉字验证码和算式验证码的方法

本文实例讲述了php实现汉字验证码和算式验证码的方法。分享给大家供大家参考。具体分析如下: 大家知道简单数字或者字母验证码很容易被破解,但是算式验证码或者中文汉字验证码不容易被破解, 所...

PHP图像处理之使用imagecolorallocate()函数设置颜色例子

在是使用PHP动态输出美丽图像的同时,也离不开颜色的设置,就像画画时需要使用调色板一样。设置图像的颜色,需要调用imagecolorallocate()函数完成。如果在图像中需要设置多种...

PHP实现补齐关闭的HTML标签

本文实例讲述了PHP实现补齐关闭的HTML标签。分享给大家供大家参考,具体如下: 很多时候,在我们做文章截取摘要的时候,如果出现HTML的内容,会出现截取的文章没有结束的HTML标签。这...