【问题标题】:PHP - Sorting ArrayObjectPHP - 排序数组对象
【发布时间】:2015-05-29 16:16:29
【问题描述】:

我在对扩展 ArrayObject 的 PHP 类中的项目进行排序时遇到问题。

我正在创建我的类,我想出添加 cmp() 函数的唯一方法是将它放在同一个文件中,但在类之外。由于 uasort 需要将函数名作为字符串的方式,我似乎无法将其放在其他任何地方。

所以我正在这样做:

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() 函数保留在类本身中?

【问题讨论】:

  • 我知道我可以称它们为不同的东西,但这似乎也不是一个很好的解决方案。
  • 创建一个 util.php 文件,其中包含此函数和其他类似的实用程序函数。然后 require_once('util.php');当你需要的时候。

标签: php sorting arrayobject


【解决方案1】:

您可以这样做,而不是调用函数,只需将其设为匿名函数。

仅限 PHP 5.3.0 或更高版本

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;
            }
        });
    }
}

由于匿名函数仅适用于 PHP 5.3.0 或更高版本,因此如果您需要针对低于 5.3.0 的 PHP 版本,这将是更兼容的选项

低于 PHP 5.3.0

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;
        }
    }

}

【讨论】:

  • 该死,这很有趣,我发誓我试过了,但没用。谢谢,这是一个完美可行的解决方案。
  • 你用的是什么版本的php?匿名函数直到 PHP 5.3.0 才可用
  • 对那些遥远的人来说很好。我在 5.3.2 上(幸运的是,总的来说很不幸)。
【解决方案2】:

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

ma​​gikMaker 4 年前 如果您想在类或对象中使用 uasort,请快速提醒一下语法:

<?php 

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

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

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

?>

【讨论】:

猜你喜欢
  • 2021-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多