PHP 向 usort 附加参数
以下代码位于一个函数中,该函数本身位于一个类中。其目的是避免每个 $filter 值有一个排序函数:
$GLOBAL['filter'] = $filter;
usort($this->data, function($arr1, $arr2) {
return ($arr1[$GLOBALS['filter']] > $arr2[$GLOBALS['filter']]) ? 1 : -1;
});
我的解决方案工作得很好,但我发现它相当不优雅。有人会想到在不诉诸 $GLOBALS 变量的情况下实现相同的目标吗?
感谢您的建议
The following code lays within a function which itself lays within a class. Its purpose is to avoid having one sorting function per $filter value :
$GLOBAL['filter'] = $filter;
usort($this->data, function($arr1, $arr2) {
return ($arr1[$GLOBALS['filter']] > $arr2[$GLOBALS['filter']]) ? 1 : -1;
});
My solution works perfectly fine, but I find it rather inelegant. Would somebody have an idea to acheive the same goal without resorting to the $GLOBALS variable ?
Thanks for your propositions
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
由于您使用的是匿名函数,因此可以将其用作闭包,如下所示:
Since you're using an anonymous function, you can use it as a closure like this:
在现代 PHP 中,有更好的工具可用。
从 PHP7 开始,太空船运算符 (
<=>
) 可用于进行 3 向比较。这比“大于/小于”2 路比较更可靠。从 PHP7.4 开始,箭头函数允许更简洁的语法,并且不再需要
use()
。代码:
如果
$filter
中的值可能不作为数组中的键存在,那么您可以使用??
(空合并运算符)回退到默认值。In modern PHP, there are better tools available.
From PHP7, the spaceship operator (
<=>
) is available to make a 3-way comparison. This is more reliable than a "greater than / less than" 2-way comparison.From PHP7.4, arrow functions allow more concise syntax and remove the need for
use()
.Code:
If value in
$filter
might not exist as a key in the arrays, then you can use??
(null coalescing operator) to fallback to a default value.