PHP 数组排序

php 数组排序

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

 

1. php - 数组排序函数

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

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

 

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

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

	$cars=array("volvo","bmw","toyota");sort($cars);

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

 

 

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

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

	$cars=array("volvo","bmw","toyota");rsort($cars);

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

	$numbers=array(4,6,2,22,11);rsort($numbers);

 

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

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

	$age=array("peter"=-->"35","ben"=>"37","joe"=>"43");
	asort($age);?>

 

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

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

	$age=array("peter"=-->"35","ben"=>"37","joe"=>"43");
	ksort($age);?>

 

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

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

	$age=array("peter"=-->"35","ben"=>"37","joe"=>"43");
	arsort($age);?>

 

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

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

	$age=array("peter"=-->"35","ben"=>"37","joe"=>"43");
	krsort($age);?>
相关文章