php数组排序的方法有哪些?
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 />";
}
?>
rsort() - 对数组进行降序排列
下面的实例将 $cars 数组中的元素按照字母降序排列:
实例
<?php
$cars=array("Volvo","BMW","Toyota");
rsort($cars);
$clength=count($cars);
for($x=0;$x<$clength;$x++)
{
echo $cars[$x];
echo "<br />";
}
?>
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 />";
}
?>
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 />";
}
?>
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 />";
}
?>
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 />";
}
?>
文章来自 www.judingjg.com