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设计模式之命令模式的深入解析

命令模式(Command),命令模式是封装一个通用操作的机制。 如果你熟悉C或PHP,你可能已经遇到过Command,它相当于程序中的:回调(callback)。回调通常使用一个函数指针...

PHP自定义函数实现assign()数组分配到模板及extract()变量分配到模板功能示例

本文实例讲述了PHP自定义函数实现assign()数组分配到模板及extract()变量分配到模板功能。分享给大家供大家参考,具体如下: 这里模拟tp框架模板变量分配与赋值操作。 ext...

PHP数据库操作四:mongodb用法分析

本文实例讲述了PHP数据库mongodb用法。分享给大家供大家参考,具体如下: 传统数据库中,我们要操作数据库数据都要书写大量的sql语句,而且在进行无规则数据的存储时,传统关系型数据库...

PHP Session机制简介及用法

PHP Session机制简介及用法

当服务器创建了一个session(session_start()),服务器将会在服务器的指定文件夹下创建一个session文件,其名称为sessionID,并当做cookie的值发送给浏...

thinkphp框架实现数据添加和显示功能

thinkphp框架实现数据添加和显示功能

最近的几篇随笔将都从thinkPHP框架的使用上着笔,好了,废话不多说,下面是干货。  这篇文章将围绕采用thinkPHP框架 向数据库中添加数据 和 在网页中显示 这两项功能...