PHP数组排序函数有哪些

PHPz
PHPz 原创
2020-09-05 09:58:05 6760浏览

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

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中文网!!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。