这个 usort cmp 函数实际上是如何工作的?
How does this usort cmp function actually work?
这里有一个答案:Combine two array and order this new array 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');
解决方案看起来很优雅,但我很困惑
return ($ad-$bd);
我的意思是没有比较运算符,它只是减去
function newFunc($a, $b) {
return($a-$b);
}
echo newFunc(5,3);
returns 2
那么这实际上是如何指示如何对数组进行排序的呢?
更新:
我按照建议进一步阅读了 usort 页面上的文档。它是否对每个元素执行此减法?它是否遍历每个数组元素并从其他元素中减去它?只是想解决这个问题。
如果您阅读 manual,您会看到:
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.
通过减去值,您可以得到正值或负值或 0 值,这样可以对值进行排序。
引用文档,usort
的 value_compare_func
是一个函数:
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
之前,自纪元以来的秒数将减少,因此从 $b
中减去它会 return 为负数。如果是在$b
之后,两者相减会return一个正数,如果相同,则相减当然return为零。
这里有一个答案:Combine two array and order this new array 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');
解决方案看起来很优雅,但我很困惑
return ($ad-$bd);
我的意思是没有比较运算符,它只是减去
function newFunc($a, $b) {
return($a-$b);
}
echo newFunc(5,3);
returns 2
那么这实际上是如何指示如何对数组进行排序的呢?
更新:
我按照建议进一步阅读了 usort 页面上的文档。它是否对每个元素执行此减法?它是否遍历每个数组元素并从其他元素中减去它?只是想解决这个问题。
如果您阅读 manual,您会看到:
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.
通过减去值,您可以得到正值或负值或 0 值,这样可以对值进行排序。
引用文档,usort
的 value_compare_func
是一个函数:
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
之前,自纪元以来的秒数将减少,因此从 $b
中减去它会 return 为负数。如果是在$b
之后,两者相减会return一个正数,如果相同,则相减当然return为零。