欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Sorting Array Values in PHP(数组排序)

程序员文章站 2022-03-18 13:12:43
复制代码 代码如下: $full_name = array(); $full_name["roger"] = "waters"; $full_name["richard"]...
复制代码 代码如下:

$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.