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

PHP数组排序函数有哪些

程序员文章站 2022-04-18 12:21:58
...

PHP数组排序函数有:1、sort函数;2、rsort函数;3、asort函数;4、ksort函数;5、arsort函数;6、krsort函数等等。

PHP数组排序函数有哪些

PHP数组排序函数

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

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

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

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

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

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

1、使用sort()

sort() 函数对数值数组进行升序排序。

<?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

2、使用rsort() 函数

rsort() 函数对数值数组进行降序排序。

<?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

3、使用asort()

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

4、使用ksort()

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

5、使用arsort()

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

6、使用krsort()

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

更多相关知识,请访问 PHP中文网!!