Home > Backend Development > PHP Tutorial > PHP数组排序函数有哪些

PHP数组排序函数有哪些

PHPz
Release: 2020-09-05 09:58:05
Original
7681 people have browsed it

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>";
   }
?>
Copy after login

输出:

BMW
Toyota
Volvo
Copy after login

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 />";
}
?>
Copy after login

输出:

Volvo
Toyota
BMW
Copy after login

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 />";
}
?>
Copy after login

输出:

Key=Peter, Value=35
Key=Ben, Value=37
Key=Joe, Value=43
Copy after login

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 />";
}
?>
Copy after login

输出:

Key=Ben, Value=37
Key=Joe, Value=43
Key=Peter, Value=35
Copy after login

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 />";
}
?>
Copy after login

输出:

Key=Joe, Value=43
Key=Ben, Value=37
Key=Peter, Value=35
Copy after login

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 />";
}
?>
Copy after login

输出:

Key=Peter, Value=35
Key=Joe, Value=43
Key=Ben, Value=37
Copy after login

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

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template