首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ArrayObject排序

ArrayObject排序
EN

Stack Overflow用户
提问于 2015-05-29 16:16:29
回答 2查看 565关注 0票数 1

对于扩展ArrayObject的PHP类中的项排序,我遇到了问题。

我正在创建我的类,我发现添加cmp()函数的唯一方法是将它放在同一个文件中,但是放在类之外。我似乎不能把它放在其他地方,因为uasort需要函数名作为字符串。

所以我要这么做:

代码语言:javascript
复制
class Test extends ArrayObject{

    public function __construct(){
        $this[] = array( 'test' => 'b' );
        $this[] = array( 'test' => 'a' );
        $this[] = array( 'test' => 'd' );
        $this[] = array( 'test' => 'c' );
    }


    public function sort(){
        $this->uasort('cmp');
    }

}

function cmp($a, $b) {
    if ($a['test'] == $b['test']) {
        return 0;
    } else {
        return $a['test'] < $b['test'] ? -1 : 1;
    }
}

如果我只使用这样的一个类,那么这很好,但是如果我使用两个类(通过自动加载或要求),那么它会中断两次调用cmp()。

我想我的意思是这似乎是个不好的方法。还有其他方法可以将cmp()函数保存在类本身中吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-05-29 16:24:49

您可以这样做,而不是调用一个函数,而是让它成为一个匿名函数。

仅限PHP 5.3.0或更高版本

代码语言:javascript
复制
class Test extends ArrayObject{

    public function __construct(){
        $this[] = array( 'test' => 'b' );
        $this[] = array( 'test' => 'a' );
        $this[] = array( 'test' => 'd' );
        $this[] = array( 'test' => 'c' );
    }


    public function sort(){
        $this->uasort(function($a, $b) {
            if ($a['test'] == $b['test']) {
                return 0;
            } else {
                return $a['test'] < $b['test'] ? -1 : 1;
            }
        });
    }
}

由于匿名函数只在PHP5.3.0或更高版本上工作,如果您需要将PHP版本定位在5.3.0以下,这将是更兼容的选项。

PHP 5.3.0以下

代码语言:javascript
复制
class Test extends ArrayObject{

    public function __construct(){
        $this[] = array( 'test' => 'b' );
        $this[] = array( 'test' => 'a' );
        $this[] = array( 'test' => 'd' );
        $this[] = array( 'test' => 'c' );
    }


    public function sort(){
        $this->uasort(array($this, 'cmp'));
    }

    public function cmp($a, $b) {
        if ($a['test'] == $b['test']) {
            return 0;
        } else {
            return $a['test'] < $b['test'] ? -1 : 1;
        }
    }

}
票数 4
EN

Stack Overflow用户

发布于 2015-05-29 16:22:34

原来这在PHP文档(用户注释部分) -> http://php.net/manual/en/function.uasort.php中是正确的。

4年前,如果您想在类或对象中使用uasort,请快速提醒magikMaker:

代码语言:javascript
复制
<?php 

// procedural: 
uasort($collection, 'my_sort_function'); 

// Object Oriented 
uasort($collection, array($this, 'mySortMethod')); 

// Objet Oriented with static method 
uasort($collection, array('self', 'myStaticSortMethod')); 

?>
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30534363

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档