百科狗-知识改变命运!
--

usort() - 使用用户自定义的比较函数对数组中的值进行排序 - php 数组函数

百变鹏仔1年前 (2023-11-21)阅读数 17#技术干货
文章标签函数

usort()

(PHP 4, PHP 5, PHP 7)

使用用户自定义的比较函数对数组中的值进行排序

说明

usort(array &$array,callable$value_compare_func): bool

本函数将用用户自定义的比较函数对一个数组中的值进行排序。如果要排序的数组需要用一种不寻常的标准进行排序,那么应该使用此函数。

Note:

If two members compare as equal, their relative order in the sorted array is undefined.Note:此函数为$array中的元素赋与新的键名。这将删除原有的键名,而不是仅仅将键名重新排序。

参数

$array

输入的数组

$cmp_function

在第一个参数小于,等于或大于第二个参数时,该比较函数必须相应地返回一个小于,等于或大于 0 的整数。

callback(mixed $a,mixed $b): intCaution

Returningnon-integervalues from the comparison function, such asfloat, will result in an internal cast tointegerof the callback's return value. So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as equal.

返回值

成功时返回TRUE,或者在失败时返回FALSE

范例

Example #1usort()例子

usort() - 使用用户自定义的比较函数对数组中的值进行排序 - php 数组函数

以上例程会输出:

0: 1
1: 2
2: 3
3: 5
4: 6

Note:

很明显在这个小例子中用sort()函数更合适。

使用多维数组的usort()例子

当排序多维数组时,$a和$b包含到数组第一个索引的引用。

以上例程会输出:

$fruits[0]: apples
$fruits[1]: grapes
$fruits[2]: lemons

Example #3usort()example using a member function of an object

以上例程会输出:

b
c
d

Example #4usort()example using aclosureto sort a multi-dimensional array

以上例程会输出:

y, a
x, b
z, c

参见

  • uasort() 使用用户自定义的比较函数对数组中的值进行排序并保持索引关联
  • 数组排序函数对比
Just wanted to show off the beauty of PHPs spaceship operator in this use case. 
When trying to do some custom sorting with objects and an anonymous function it wasn't entirely clear how this usort function works. I think it probably uses a quicksort in the background. Basically it actually moves the $b variable up or down in respect to the $a variable. It does NOT move the $a variable inside the callback function. This is key to getting your logic right in the comparisons.
If you return -1 that moves the $b variable down the array, return 1 moves $b up the array and return 0 keeps $b in the same place. 
To test I cut down my code to sorting a simple array from highest priority to lowest.

Output:
b (8) is higher priority than a (3), moving b up array
b (5) is higher priority than a (3), moving b up array
b (7) is higher priority than a (3), moving b up array
a (3) is same priority as b (3), keeping the same
a (8) is higher priority than b (3), moving b down array
b (8) is higher priority than a (7), moving b up array
b (8) is higher priority than a (5), moving b up array
b (8) is higher priority than a (3), moving b up array
a (5) is higher priority than b (3), moving b down array
a (7) is higher priority than b (5), moving b down array
Sorted priorities:
array(5) {
 [0]=> int(8)
 [1]=> int(7)
 [2]=> int(5)
 [3]=> int(3)
 [4]=> int(3)
}
You can also sort multi-dimensional array for multiple values like as

Output:
Array
(
  [0] => Array
    (
      [name] => Jackson
      [nick_name] => jack
      [availability] => 1
      [is_fav] => 1
    )
  [1] => Array
    (
      [name] => David
      [nick_name] => dav07
      [availability] => 0
      [is_fav] => 1
    )
  [2] => Array
    (
      [name] => Zen
      [nick_name] => zen
      [availability] => 1
      [is_fav] => 0
    )
  [3] => Array
    (
      [name] => Rohit
      [nick_name] => rod
      [availability] => 0
      [is_fav] => 0
    )
  [4] => Array
    (
      [name] => Sally
      [nick_name] => sal
      [availability] => 0
      [is_fav] => 0
    )
)
You can also sort multi-dimensional array for multiple values like as

output:
Array
(
  [0] => Array
    (
      [id] => 1
      [age] => 1
      [sex] => 6
      [name] => a
    )
  [1] => Array
    (
      [id] => 4
      [age] => 2
      [sex] => 1
      [name] => d
    )
  [2] => Array
    (
      [id] => 2
      [age] => 3
      [sex] => 1
      [name] => c
    )
  [3] => Array
    (
      [id] => 3
      [age] => 3
      [sex] => 1
      [name] => b
    )
)
this is a new multisort function for sorting on multiple subfield like it will be in sql : 'ORDER BY field1, field2'
number of sort field is undefined

output:
Array
(
  [0] => Array
    (
      [soc] => 1
      [code] => 1
    )
  [1] => Array
    (
      [soc] => 1
      [code] => 1
    )
  [2] => Array
    (
      [soc] => 1
      [code] => 2
    )
  [3] => Array
    (
      [soc] => 2
      [code] => 1
    )
  [4] => Array
    (
      [soc] => 2
      [code] => 5
    )
  [5] => Array
    (
      [soc] => 3
      [code] => 1
    )
  [6] => Array
    (
      [soc] => 3
      [code] => 2
    )
)
I wrote a wrapper for usort that lets you use something similar to an SQL ORDER BY clause. It can sort arrays of associative arrays and arrays of objects and I think it would work with some hybrid case.
Example of how the function works:

To sort an array of objects you would do something like:
Utility::orderBy($objectAry, 'getCreationDate() DESC, getSubOrder() ASC');
This would sort an array of objects that have methods getCreationDate() and getSubOrder().
Here is the function: 
The easiest way to compare two integers is just to take the second away from the first. For example, say you wanted to sort by an integer property of an object. Your comparison function would look like this:

This works because you don't necessarily have to return -1, 0 or 1, the manual states any integer less than, equal to or greater than 0 is OK.
usort returns null when the sorting function is not (yet) defined. The function has to be defined before usort is called, afterwards doesn't work.
As the manual says, "If two members compare as equal, their order in the sorted array is undefined." This means that the sort used is not "stable" and may change the order of elements that compare equal.
Sometimes you really do need a stable sort. For example, if you sort a list by one field, then sort it again by another field, but don't want to lose the ordering from the previous field. In that case it is better to use usort with a comparison function that takes both fields into account, but if you can't do that then use the function below. It is a merge sort, which is guaranteed O(n*log(n)) complexity, which means it stays reasonably fast even when you use larger lists (unlike bubblesort and insertion sort, which are O(n^2)). 
This function will sort on more then one values, test and have fun

鹏仔微信 15129739599 鹏仔QQ344225443 鹏仔前端 pjxi.com 共享博客 sharedbk.com

免责声明:我们致力于保护作者版权,注重分享,当前被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理!邮箱:344225443@qq.com)

图片声明:本站部分配图来自网络。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!

内容声明:本文中引用的各种信息及资料(包括但不限于文字、数据、图表及超链接等)均来源于该信息及资料的相关主体(包括但不限于公司、媒体、协会等机构)的官方网站或公开发表的信息。部分内容参考包括:(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供参考使用,不准确地方联系删除处理!本站为非盈利性质站点,本着为中国教育事业出一份力,发布内容不收取任何费用也不接任何广告!)