How does this usort cmp function actually work?

五迷三道 提交于 2019-12-12 17:22:53

问题


There's an answer here: Combine two array and order this new array by date

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);

returns 2

So how does this actually indicate how to sort the arrays?

Update:

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.


回答1:


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.

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.




回答2:


If you read a manual, you see:

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.

By substracting values you get either positive or negative or 0 value, which allows to sort values.



来源:https://stackoverflow.com/questions/39243553/how-does-this-usort-cmp-function-actually-work

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!