Home  >  Article  >  Backend Development  >  如何运用PHP函数usort()实现自定义排序_PHP教程

如何运用PHP函数usort()实现自定义排序_PHP教程

WBOY
WBOYOriginal
2016-07-15 13:29:501287browse

在中进行数组排序的方式有许多种,包括按照值排序,按照关键字排序,自然语言排序等等。今天我们要教给大家的是运用PHP函数usort()来实现自定义的数组排序。你可以通过创建你自己的比较函数,并把它传递给PHP函数usort(),如果第一个参数比第二个参数“小”的话,比较函数必须返回一个比0小的数,如果第一参数比第二个参数“大”的话,比较函数应该返回一个比0大的数。

Listing I就是PHP函数usort()的一个例子,在这个例子中根据它们的长度对数组元素进行排序,最短的项放在最前面:

  1. php 
  2. $data = array("joe@host.com", "john.doe@gh.co.uk",
    "asmithsonian@us.info", "jay@zoo.tw");usort($data, 'sortByLen');  
  3. print_r($data); function sortByLen($a, $b) {  
  4. if (strlen($a) == strlen($b)) {  
  5. return 0;  
  6. } else {  
  7. return (strlen($a) > strlen($b)) ? 1 : -1;  
  8. }  
  9. }  
  10. ?> 

这样,就创建了我们自己的比较函数,这个函数使用PHP函数usort()比较每一个字符串的个数,然后分别返回1,0或-1.这个返回值是决定元素排列的基础。下面是它的输出结果:

Array ([0] => jay@zoo.tw

[1] => joe@host.com

[2] => john.doe@gh.co.uk

[3] => asmithsonian@us.info

)

希望大家能够通过这段示例代码学到PHP函数usort()的具体使用方式。


www.bkjia.comtruehttp://www.bkjia.com/PHPjc/446347.htmlTechArticle在中进行数组排序的方式有许多种,包括按照值排序,按照关键字排序,自然语言排序等等。今天我们要教给大家的是运用PHP函数usort()来实...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn