PHP如何使用usort()函数?代码示例

2021年3月30日10:22:03 发表评论 630 次浏览

PHP附带了许多内置函数, 这些函数用于以更简单的方式对数组进行排序。在这里, 我们将讨论一个新的函数usort()。 PHP中的usort()函数通过使用用户定义的比较函数对给定的数组进行排序。如果我们要以新的方式对数组进行排序, 则此函数很有用。此函数将从零开始的新整数键分配给数组中存在的元素, 并且旧键会丢失。

语法如下:

boolean usort( $array, "function_name");

参数:此函数接受上面语法中所示的两个参数, 并在下面进行描述:

  1. $数组:此参数指定你要排序的数组。
  2. function_name:此参数指定用户定义函数的名称, 该函数将比较值并对参数指定的数组进行排序$数组。该函数根据以下条件返回整数值。如果两个参数相等, 则返回0;如果第一个参数大于第二个, 则返回1;如果第一个参数小于第二个, 则返回-1。

返回值:此函数返回值的布尔类型。如果成功则返回TRUE, 失败则返回FALSE。

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

<?php
  
     // PHP program to illustrate usort() function
  
     // This is the user-defined function used to compare
     // values to sort the input array
     function comparatorFunc( $x , $y )
     {   
         // If $x is equal to $y it returns 0
         if ( $x == $y )
             return 0;
      
         // if x is less than y then it returns -1
         // else it returns 1    
         if ( $x < $y )
             return -1;
         else
             return 1;
     }
      
     // Input array
     $arr = array (2, 9, 1, 3, 5); 
  
     usort( $arr , "comparatorFunc" );
      
     print_r( $arr );
  
?>

输出如下:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 5
    [4] => 9
)

参考:http://php.net/manual/en/function.usort.php


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: