PHP 数组比较函数如何工作?
我有以下功能:
public static function CompareGroupReportEntries($a, $b)
{
if ($a->visibility == $b->visibility) {
return 0;
} else{
return $a->visibility < $b->visibility ? 1 : -1;
}
}
它工作正常,我明白它的作用。但是我很难理解它是如何工作的。它在下面一行被调用;
usort($reports, "Utilities::CompareGroupReportEntries");
它是在循环之外调用的,那么它如何对数组中的所有对象进行排序呢?参数 $a 和 $b 的作用是什么?
感谢您的帮助。
I have the following function:
public static function CompareGroupReportEntries($a, $b)
{
if ($a->visibility == $b->visibility) {
return 0;
} else{
return $a->visibility < $b->visibility ? 1 : -1;
}
}
It works fine and I understand what it does. However I have difficulty in understanding it how it works. It is called on the following line;
usort($reports, "Utilities::CompareGroupReportEntries");
It is called outside of a loop, so how does it manage to sort all the objects in the array? What are the parameters $a and $b for?
Appreciate the help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的答案在这里:PHP 的 USORT 回调函数参数
YOur answer here: PHP's USORT Callback Function Parameters
它比较数组的元素以确定它们的位置。
所以 $a 和 $b 是列表的元素,并且从 CompareGroupReportEntries 函数的结果中它可以知道哪个值更大,因此它可以将其向上或向下移动
it compares the elements of the array to determine their position.
so $a and $b are to elements of the list and from the result of the CompareGroupReportEntries-function it can say which value is bigger, so it can move it one up or down
函数 usort 是一个排序函数,它接受一个数组和一个回调函数。这里你的函数CompareGroupReportEntries是一个回调函数。 PHP 并不关心数组元素是数字还是字符串。它需要您的回调函数来实现数组值的排序标准。如果你熟悉 C,那么有一个
quicksort
函数,它也带有一个回调函数The function usort is a sorting function which takes an array and a callback function. here your function
CompareGroupReportEntries
is a callback function. PHP doesnt care whether your array elements are nubers or strings. it expects your callback function for the sorting criteria of the values of your array. iIf u are familiar with C then there is aquicksort
function which also takes a callback function