将 PHP usort 与条件结果结合使用
长话短说,我需要使用 usort 对对象数组进行排序,并且需要告诉 usort 按对象中的哪些字段进行排序。
显而易见的解决方案是创建数十个单独的 usort 排序函数,但这似乎有点多余且丑陋。大多数时候,对象将按 $_GET 的输入进行排序,但并非总是如此,因此我不想直接按 $_GET 变量进行排序。
usort函数是否可以使用当前类的排序函数?像这样的东西
<?php
class myClass
{
public $myArray;
private $by;
public function filter($by)
{
$this->by = $by;
usort($this->myArray, /* Somehow point to the following function: */ );
}
private function srt($a, $b)
{
$c = $this->by; // <- reaching a third variable
// ...
}
}
?>
Long story short, I need to sort an array of objects using usort, and I need to tell usort which fields in the objects to sort by.
The obvious solution is to create tens of separate usort sorting functions, but this seems sort of redundant and ugly. Most of the time, objects will be sorted by input from $_GET, but not always, so I don't want to sort by $_GET variables directly.
Is it possible for the usort function to use the current class' sorting function? Something like this
<?php
class myClass
{
public $myArray;
private $by;
public function filter($by)
{
$this->by = $by;
usort($this->myArray, /* Somehow point to the following function: */ );
}
private function srt($a, $b)
{
$c = $this->by; // <- reaching a third variable
// ...
}
}
?>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,将对象数组和方法名称传递给
usort()
:编辑: 我已经测试并发现,只要您这样做,这将适用于私有方法在包含私有方法的同一类中调用
usort()
。Yes, pass an array of the object and the method name to
usort()
:EDIT: I've tested and found that this will work with private methods as long as you call
usort()
in the same class that contains the private method.您还可以通过其他方式从方法内部调用 usort 函数。
Other ways you can call usort function from inside a method.