此usort cmp函数实际上如何工作? [英] How does this usort cmp function actually work?

查看:52
本文介绍了此usort cmp函数实际上如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里有一个答案:将两个数组和按日期排序此新数组

它说明了如何合并两个数组,然后按日期排序。

It explains how two arrays can be merged and then sorted by date.

function cmp($a, $b){
    $ad = strtotime($a['date']);
    $bd = strtotime($b['date']);
    return ($ad-$bd);
}
$arr = array_merge($array1, $array2);
usort($arr, 'cmp');

解决方案看起来很优雅,但我对

the solution looks quite elegant, but I'm confused by

return ($ad-$bd);

我的意思是没有比较运算符,它只是减去

I mean there's no comparison operator, it just subtracts

function newFunc($a, $b) {
    return($a-$b);
}

echo newFunc(5,3);

返回2

这怎么办

更新:

我进一步阅读了usort页面上的文档:建议。它是否对每个元素执行此减法?是否会遍历每个数组元素并从其他元素中减去它?

I read further the documentation on the usort page as suggested. Does it perform this subtraction with each of the elements? Does it iterate through each array element and subtracts it from other elements? Just trying to wrap my head around this.

推荐答案

要引用文档,请使用 usort value_compare_func 是以下函数:

To quote the documentation, a usort's value_compare_func is a function that:


如果第一个比较函数必须返回小于,等于或大于零的整数参数被认为分别小于,等于或大于第二个。

The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

在这种情况下,两个日期都转换为Unix时间戳,即自该纪元以来的秒数。如果 $ a $ b 之前,则自该时期以来的秒数将减少,因此从<$ c中减去它$ c> $ b 将返回负数。如果在 $ b 之后,将两者相减将返回正数,如果它们相同,则相减当然会返回零。

In this case, both dates are converted to a Unix timestamp, i.e., the number of seconds since the epoch. If $a comes before $b, it will have less seconds since the epoch, so subtracting it from $b will return a negative number. If it comes after $b, subtracting the two will return a positive number, and if they are the same, the subtraction will of course return zero.

这篇关于此usort cmp函数实际上如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆