PHP 数组排序

2019年11月1日08:00:13 Comment 753

PHP 数组排序

数组中的元素可以按字母或数字顺序进行降序或升序排列。

PHP - 数组排序函数

sort() - 对数组进行升序排列

rsort() - 对数组进行降序排列

asort() - 根据关联数组的值,对数组进行升序排列

ksort() - 根据关联数组的键,对数组进行升序排列

arsort() - 根据关联数组的值,对数组进行降序排列

krsort() - 根据关联数组的键,对数组进行降序排列

sort() - 对数组进行升序排列

下面的实例将 $cars 数组中的元素按照字母升序排列:

<?php
$cars=array("Volvo","BMW","Toyota");
sort($cars);

$clength=count($cars);
for($x=0;$x<$clength;$x++)
{
echo $cars[$x];
echo "<br />";
}
?>

BMW

Toyota

Volvo

下面的实例将 $numbers 数组中的元素按照数字升序排列:

<?php
$numbers=array(4,6,2,22,11);
sort($numbers);

$arrlength=count($numbers);
for($x=0;$x<$arrlength;$x++)
{
echo $numbers[$x];
echo "<br />";
}
?>

2

4

6

11

22

rsort() - 对数组进行降序排列

下面的实例将 $cars 数组中的元素按照字母降序排列:

<?php
$cars=array("Volvo","BMW","Toyota");
rsort($cars);

$clength=count($cars);
for($x=0;$x<$clength;$x++)
{
echo $cars[$x];
echo "<br />";
}
?>

Volvo

Toyota

BMW

下面的实例将 $numbers 数组中的元素按照数字降序排列:

<?php
$numbers=array(4,6,2,22,11);
rsort($numbers);

$arrlength=count($numbers);
for($x=0;$x<$arrlength;$x++)
{
echo $numbers[$x];
echo "<br />";
}
?>

22

11

6

4

2

asort() - 根据数组的值,对数组进行升序排列

下面的实例根据数组的值,对关联数组进行升序排列:

<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");

asort($age);

foreach($age as $x=>$x_value)
{
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br />";
}
?>

Key=Peter, Value=35

Key=Ben, Value=37

Key=Joe, Value=43

ksort() - 根据数组的键,对数组进行升序排列

下面的实例根据数组的键,对关联数组进行升序排列:

<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
ksort($age);

foreach($age as $x=>$x_value)
{
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br />";
}
?>

Key=Ben, Value=37

Key=Joe, Value=43

Key=Peter, Value=35

arsort() - 根据数组的值,对数组进行降序排列

下面的实例根据数组的值,对关联数组进行降序排列:

<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
arsort($age);

foreach($age as $x=>$x_value)
{
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br />";
}
?>

Key=Joe, Value=43

Key=Ben, Value=37

Key=Peter, Value=35

krsort() - 根据数组的键,对数组进行降序排列

下面的实例根据数组的键,对关联数组进行降序排列:

<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
krsort($age);

foreach($age as $x=>$x_value)
{
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br />";
}
?>

Key=Peter, Value=35

Key=Joe, Value=43

Key=Ben, Value=37

  • 我的微信
  • 一起交流技术
  • weinxin
  • 我的微信公众号
  • 一起交流技术
  • weinxin
  • A+
Categories:PHP

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: