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设计模式之适配器模式原理与用法。分享给大家供大家参考,具体如下: 一、什么是适配器模式 适配器模式有两种:类适配器模式和对象适配器模式。其中类适配器模式使用继承方式,...

php ajax异步读取rss文档数据

RSS(Really Simple Syndication)是一种描述和同步网站内容的格式,是使用最广泛的XML应用。RSS搭建了信息迅速传播的一个技术平台,使得每个人都成为潜在的信息提...

php基于数组函数实现关联表的编辑操作示例

本文实例讲述了php基于数组函数实现关联表的编辑操作。分享给大家供大家参考,具体如下: 需求为,在创建学校时,需要添加应用,于是创建了个学校应用关联表,编辑学校并提交时,后台需要判断更新...

求PHP数组最大值,最小值的代码

复制代码 代码如下: <?php $fruits = array("155::vbscript:://www.jb51.net/list/list_114_1.htm", "1::...

PHP exif扩展方法开启详解

服务器配置说明: 1.在php.ini文件中找到;extension=php_exif.dll,去掉前面的分号 2.在php.ini文件中找到;extension=php_mbstrin...