PHP 数组排序
最编程
2024-03-23 13:40:57
...
数组中的元素可以按字母或数字顺序进行降序或升序排列。
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 />"; } ?>
点击 "运行实例" 按钮查看在线实例
下面的实例将 $numbers 数组中的元素按照数字升序排列:
实例
<?php $numbers=array(4,6,2,22,11); sort($numbers); $arrlength=count($numbers); for($x=0;$x<$arrlength;$x++) { echo $numbers[$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 />"; } ?>
点击 "运行实例" 按钮查看在线实例
下面的实例将 $numbers 数组中的元素按照数字降序排列:
实例
<?php $numbers=array(4,6,2,22,11); rsort($numbers); $arrlength=count($numbers); for($x=0;$x<$arrlength;$x++) { echo $numbers[$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 />"; } ?>
点击 "运行实例" 按钮查看在线实例
完整的 PHP Array 参考手册
如需查看所有数组函数的完整参考手册,请访问我们的 PHP Array 参考手册。
该参考手册提供了每个函数的简要描述和应用实例!
推荐阅读
-
CSS3 - 即时增强网页风格的工具 - 免费在线视频教程 - php.cn
-
php 实现 修改配置文件的示例
-
用 PHP 开发将简单文件上传到 MySql 数据库 (a)
-
PHP 超级棒的无限分类生成树方法
-
如何使用 PHP 开发简单的在线问卷功能
-
使用 CURL 在 php 中构建 POST 请求
-
替代运算符和标记 - [ C 语言中文开发手册 ] - 本地在线手册 - php中文网
-
MySQL tinytext、text、mediumtext 和 longtext 类型 - PHP+MySql - php中文网博客
-
以史为鉴:排序算法的新见解
-
Redux 排序与分析 [I: 减速器与调度]。