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 /* 功能:获取页面内容,存储下来阅读; lost63 */...

php连接sftp的作用以及实例代码

sftp 协议 使用SSH协议进行FTP传输的协议叫SFTP(安全文件传输)Sftp和Ftp都是文件传输协议。 区别: sftp是ssh内含的协议(ssh是加密的telnet协议),只...

解析php中用PHPMailer来发送邮件的示例(126.com的例子)

<?phprequire_once('../class.phpmailer.php');$mail= new PHPMailer();$body= "我终于发送邮件成功了!呵呵!g...

php页面缓存ob系列函数介绍

这里有缓存技术的简单介绍:https://www.jb51.net/article/4965.htm   php页面缓存主要用到的是ob系列函数,如ob_start(),ob_end_f...

php简单随机字符串生成方法示例

本文实例讲述了php简单随机字符串生成方法。分享给大家供大家参考,具体如下: <?php function rand_str($length,$p='all'){ $...