PHP 数组排序

PHP 教程 · 2019-01-18 16:56:23

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

PHP - 数组排序函数

在本章中,我们将一一介绍下列 PHP 数组排序函数:

  • sort() - 对数组进行升序排列
  • rsort() - 对数组进行降序排列
  • asort() - 根据关联数组的值,对数组进行升序排列
  • ksort() - 根据关联数组的键,对数组进行升序排列
  • arsort() - 根据关联数组的值,对数组进行降序排列
  • krsort() - 根据关联数组的键,对数组进行降序排列

sort() - 对数组进行升序排列

下面的实例将 $cars 数组中的元素按照字母升序排列:

<?php
$cars=array("Volvo","BMW","Toyota");
sort($cars);
?>

下面的实例将 $numbers 数组中的元素按照数字升序排列:

<?php
$numbers=array(4,6,2,22,11);
sort($numbers);
?>

rsort() - 对数组进行降序排列

下面的实例将 $cars 数组中的元素按照字母降序排列:

<?php
$cars=array("Volvo","BMW","Toyota");
rsort($cars);
?>

下面的实例将 $numbers 数组中的元素按照数字降序排列:

<?php
$numbers=array(4,6,2,22,11);
rsort($numbers);
?>

asort() - 根据数组的值,对数组进行升序排列

下面的实例根据数组的值,对关联数组进行升序排列:

<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
asort($age);
?>

ksort() - 根据数组的键,对数组进行升序排列

下面的实例根据数组的键,对关联数组进行升序排列:

<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
ksort($age);
?>

arsort() - 根据数组的值,对数组进行降序排列

下面的实例根据数组的值,对关联数组进行降序排列:

<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
arsort($age);
?>

krsort() - 根据数组的键,对数组进行降序排列

下面的实例根据数组的键,对关联数组进行降序排列:

<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
krsort($age);
?>

完整的 PHP Array 参考手册

如需查看所有数组函数的完整参考手册,请访问我们的 PHP Array 参考手册。

该参考手册提供了每个函数的简要描述和应用实例!

点击查看所有 PHP 教程 文章: https://www.codercto.com/courses/l/5.html

查看所有标签

Introduction to Graph Theory

Introduction to Graph Theory

Douglas B. West / Prentice Hall / 2000-9-1 / USD 140.00

For undergraduate or graduate courses in Graph Theory in departments of mathematics or computer science. This text offers a comprehensive and coherent introduction to the fundamental topics of graph ......一起来看看 《Introduction to Graph Theory》 这本书的介绍吧!

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

html转js在线工具
html转js在线工具

html转js在线工具