PHP Array Sorting
- Previous page PHP Arrays
- Next page PHP Superglobal
数组中的元素能够以字母或数字顺序进行升序或降序排序。
PHP - 数组的排序函数
在本节中,我们将学习如下 PHP 数组排序函数:
- sort() - 以升序对数组排序
- rsort() - 以降序对数组排序
- asort() - 根据值,以升序对关联数组进行排序
- ksort() - 根据键,以升序对关联数组进行排序
- arsort() - 根据值,以降序对关联数组进行排序
- krsort() - 根据键,以降序对关联数组进行排序
对数组进行升序排序 - sort()
下面的例子按照字母升序对数组 $cars 中的元素进行排序:
Example
<?php $cars=array("porsche","BMW","Volvo"); sort($cars); ?>
The following example sorts the elements of the array $numbers in ascending order by number:
Example
<?php $numbers=array(3,5,1,22,11); sort($numbers); ?>
Sort the array in descending order - rsort()
The following example sorts the elements of the array $cars in descending order by letter:
Example
<?php $cars=array("porsche","BMW","Volvo"); rsort($cars); ?>
The following example sorts the elements of the array $numbers in descending order by number:
Example
<?php $numbers=array(3,5,1,22,11); rsort($numbers); ?>
Sort the array by value in ascending order - asort()
The following example sorts the associated array in ascending order by value:
Example
<?php $age=array("Bill"=>"63","Steve"=>"56","Elon"=>"47"); asort($age); ?>
Sort the array by key in ascending order - ksort()
The following example sorts the associated array in ascending order by key:
Example
<?php $age=array("Bill"=>"63","Steve"=>"56","Elon"=>"47"); ksort($age); ?>
Sort the array by value in descending order - arsort()
The following example sorts the associated array in descending order by value:
Example
<?php $age=array("Bill"=>"63","Steve"=>"56","Elon"=>"47"); arsort($age); ?>
Sort the array by key in descending order - krsort()
The following example sorts the associated array in descending order by key:
Example
<?php $age=array("Bill"=>"63","Steve"=>"56","Elon"=>"47"); krsort($age); ?>
Complete PHP Array Reference Manual
For a complete reference manual of array functions, please visit our PHP Array Reference Manual.
This reference manual includes a brief description and usage examples for each function.
- Previous page PHP Arrays
- Next page PHP Superglobal