当前位置:  首页>> 技术小册>> PHP合辑3-数组函数

sort()函数是PHP中的一个内置函数,用于按升序对数组进行排序,即从小到大。它对实际数组进行排序,因此更改会反映在原始数组本身中。该函数为我们提供了6种排序类型,根据这些类型可以对数组进行排序。

语法:

bool sort($array, sorting_type)

参数:

$array - 我们想要排序的数组参数。这是必需的参数
sorting_type - 这是一个可选参数。有以下6种排序类型:

SORT_REGULAR - 当我们在sorting_type参数中传递0或SORT_REGULAR时,数组中的项将正常比较。

SORT_NUMERIC - 当我们在sorting_type参数中传递1或SORT_NUMERIC时,数组中的项将按数值进行比较

SORT_STRING - 当我们在sorting_type参数中传递2或SORT_STRING时,数组中的项将按字符串进行比较

SORT_LOCALE_STRING - 当我们在sorting_type参数中传递3或SORT_LOCALE_STRING时,数组中的项将根据当前区域设置作为字符串进行比较

SORT_NATURAL - 当我们在sorting_type参数中传递4或SORT_NATURAL时,数组中的项将作为字符串使用自然排序进行比较

SORT_FLAG_CASE - 当我们在sorting_type参数中传递5或SORT_FLAG_CASE时,数组中的项将作为字符串进行比较。这些项被视为不区分大小写,然后进行比较。它可以使用位运算符|与SORT_NATURAL或SORT_STRING一起使用。

返回值:它返回一个布尔值,成功时为TRUE,失败时为FALSE。它按升序对作为参数传递的原始数组进行排序。

示例:

  1. Input : $array = [3, 4, 1, 2]
  2. Output :
  3. Array
  4. (
  5. [0] => 1
  6. [1] => 2
  7. [2] => 3
  8. [3] => 4
  9. )
  10. Input : $array = ["geeks2", "raj1", "striver3", "coding4"]
  11. Output :
  12. Array
  13. (
  14. [0] => coding4
  15. [1] => geeks2
  16. [2] => raj1
  17. [3] => striver3
  18. )

下面的程序说明了PHP中的sort()函数:

程序1:演示sort()函数使用的程序。

  1. <?php
  2. // PHP program to demonstrate the use of sort() function
  3. $array = array(3, 4, 2, 1);
  4. // sort function
  5. sort($array);
  6. // prints the sorted array
  7. print_r($array);
  8. ?>

output:

  1. Array
  2. (
  3. [0] => 1
  4. [1] => 2
  5. [2] => 3
  6. [3] => 4
  7. )

程序2:演示sort()函数用于按字符串大小写敏感排序的程序。

  1. <?php
  2. // PHP program to demonstrate the use of sort() function
  3. // sorts the string case-sensitively
  4. $array = array("geeks", "Raj", "striver", "coding", "RAj");
  5. // sort function, sorts the string case-sensitively
  6. sort($array, SORT_STRING);
  7. // prints the sorted array
  8. print_r($array);
  9. ?>

output:

  1. Array
  2. (
  3. [0] => RAj
  4. [1] => Raj
  5. [2] => coding
  6. [3] => geeks
  7. [4] => striver
  8. )

程序3:演示sort()函数用于按字符串大小写不敏感排序的程序。

  1. <?php
  2. // PHP program to demonstrate the use
  3. // of sort() function sorts the string
  4. // case-insensitively
  5. $array = array("geeks", "Raj", "striver", "coding", "RAj");
  6. // sort function, sorts the
  7. // string case-insensitively
  8. sort($array, SORT_STRING | SORT_FLAG_CASE);
  9. // prints the sorted array
  10. print_r($array);
  11. ?>

output:

  1. Array
  2. (
  3. [0] => coding
  4. [1] => geeks
  5. [2] => Raj
  6. [3] => RAj
  7. [4] => striver
  8. )

该分类下的相关小册推荐: