将 PHP usort 与条件结果结合使用

发布于 2024-09-24 14:36:11 字数 644 浏览 2 评论 0原文

长话短说,我需要使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

浅语花开 2024-10-01 14:36:11

是的,将对象数组和方法名称传递给 usort()

usort($this->myArray, array($this, 'srt'));

编辑: 我已经测试并发现,只要您这样做,这将适用于私有方法在包含私有方法的同一类中调用 usort()

Yes, pass an array of the object and the method name to usort():

usort($this->myArray, array($this, 'srt'));

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.

倾城花音 2024-10-01 14:36:11

您还可以通过其他方式从方法内部调用 usort 函数。

usort($this->myArray, 'myClass::srt');
usort($this->myArray, array(self::class, 'srt'));

Other ways you can call usort function from inside a method.

usort($this->myArray, 'myClass::srt');
usort($this->myArray, array(self::class, 'srt'));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文