帮助优化 PHP 中对 usort 函数的调用
这是我对 usort()
的回调
public function sortProperties($a, $b) {
$sortA = inflector::camelize(str_replace('-', '_', $this->sortBy));
$sortB = inflector::camelize(str_replace('-', '_', $this->sortBy));
$a = Arr::get($a, $sortA);
$b = Arr::get($b, $sortB);
if (is_numeric($a) AND is_numeric($b)) {
return $a < $b;
} else {
return strcasecmp($a, $b);
}
}
通常,当我看到代码中任意的前两行时,它会向我尖叫:重构! em> 我想这是因为它们是相同的。
我知道我可以创建一个函数 getCamelized()
,但我不认为我会在此之外再次使用它。
有没有办法把这4行变成2行? func_get_args()
或 array_walk()
可以帮助我吗?
另外,这个排序功能有什么问题吗?
This is my callback for my usort()
public function sortProperties($a, $b) {
$sortA = inflector::camelize(str_replace('-', '_', $this->sortBy));
$sortB = inflector::camelize(str_replace('-', '_', $this->sortBy));
$a = Arr::get($a, $sortA);
$b = Arr::get($b, $sortB);
if (is_numeric($a) AND is_numeric($b)) {
return $a < $b;
} else {
return strcasecmp($a, $b);
}
}
Usually, when I see the first 2 lines in any of my code, it screams to me: refactor! I guess it's because they are identical.
I know I could make a function getCamelized()
, but I don't think I'd use it again outside of this.
Is there a way to turn those 4 lines into 2? Could func_get_args()
or array_walk()
help me here?
Also, is there anything wrong about this sorting function?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对于其他两行:
至于排序,至少对我来说似乎没问题。
And for other two lines:
As for sort, it seems to be fine at least to me.
$sortA == $sortB
所以这部分只是重复。无论您在哪里设置$this->sortBy
,都计算一次$sortA
。您所遇到的Arr::get
行。返回 $a < $b;
似乎是错误的,你应该返回一个 -ve, 0, +ve 数字。类似的事情。主要思想是让骆驼化部分脱离循环。
$sortA == $sortB
so that part is just duplication. Calculate$sortA
once wherever you set$this->sortBy
. TheArr::get
lines you're stuck with. Thereturn $a < $b;
seems wrong, you should be returning a -ve, 0, +ve number.Something like that. The main idea to get the camelizing part out of the loop.
请注意,
strcasecmp
将返回一个 int(1、0 或 -1),<
将返回一个布尔值。您确实需要使用其中之一。另请注意,strnatcasecmp
可能会为您提供您想要的数字和字符串行为,因此请尝试以下操作:Be aware that
strcasecmp
will return an int (1, 0, or -1) and<
will return a boolean. You really need to be using one or the other. Also note thatstrnatcasecmp
will probably give you the behavior you want for both numbers and strings so try this one: