得水小筑

PHP学习笔记-PHP 数组排序

PHP数组中的元素可以按字母或数字顺序进行降序或升序排列。PHP数组排序函数方法有:sort()、rsort() 、asort() 、ksort()、arsort()、krsort()。

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

PHP - 数组排序函数

sort对数组进行升序排列

<?php
$cars=array("Volvo","BMW","Toyota");
sort($cars);
$clength=count($cars);
for($x=0;$x<$clength;$x++)
{
  echo $cars[$x];
  echo "<br />";
}
?>

rsort对数组进行降序排列

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

小插曲

腾云先锋TDP(TDP,Tencent Cloud Developer Pioneer)是腾讯云 GTS 官方组建并运营的技术开发者群体。这里有最专业的开发者&客户,能与产品人员亲密接触,专有的问题&需求反馈渠道,有一群志同道合的兄弟姐妹。来加入属于我们开发者的社群吧 。进群时可以跟管理员说是从本站过来的

当前页面是本站的「Google AMP」版。查看和发表评论请点击:完整版 »