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快速排序原理与实现方法分析

本文实例讲述了php快速排序方法。分享给大家供大家参考,具体如下: <?php $n = array('13','14','55','10','54','2','79'...

php实现多站点共用session实现单点登录的方法详解

php实现多站点共用session实现单点登录的方法详解

本文实例讲述了php实现多站点共用session实现单点登录的方法。分享给大家供大家参考,具体如下: 最近闲来无事,总结整理下单点登录的问题。 单点登录的基本原理为:客户端共享sesio...

Ubuntu 16.04下安装PHP 7过程详解

前言 最近由于换了硬盘重装了(升级)系统到Ubuntu16.04之后,开发环境也要重新安装,其实16.04源里面默认的PHP版本就是7.x,但是有个问题就是没有OCI扩展,有项目需要使用...

php_imagick实现图片剪切、旋转、锐化、减色或增加特效的方法

本文实例讲述了php_imagick实现图片剪切、旋转、锐化、减色或增加特效的方法。分享给大家供大家参考。具体分析如下: 一个可以供PHP调用ImageMagick功能的PHP扩展。使用...

php自动获取目录下的模板的代码

目录下必须有default.gif(此图为模板缩略图)的才为合法的模板 复制代码 代码如下: function get_template () { $template = array (...