2012-03-27 72 views
1

我很想使用PHP Lithium对嵌入式MongoDB对象进行排序。我有一个模型“线程”,看起来几乎是这样的:PHP锂:对嵌入式对象数组进行排序

{ 
    "_id": ObjectId("4f71bf4618b602580f000009"), 
    "postings": [ 
     {text: "a", upvotes: 15, /*...*/}, 
     {text: "b", upvotes: 23}, 
     {text: "c", upvotes: 16}, 
     {text: "d", upvotes: 42} 
    ], 
    // bla 
} 

现在我想根据他们的upvotes排序张贴。我已经写了一个方法,大致做什么,我想:

public function postings_sort_by_upvotes($thread) { 
    $postings = $thread->postings->to('array'); 
    usort($postings, function($a, $b) { 
         return ($a['upvotes'] > $b['upvotes'] ? 1 : -1); 
        }); 
    return $postings; 
} 

这工作,但显然它返回的帖子作为一个普通数组,而无序的帖子是一个lithium\data\collection\DocumentArray类型。

难道我真的需要与一个数组而不是一个对象挣扎吗?或者有没有一种方法可以让我对它们进行排序而不会丢失原始数据类型?

回答

4

A DocumentArray对象是Collection,并且希望锂集合可以排序。 您可以在$collection不同的方式调用sort()

$collection->sort('field'); //sort naturally by the given field 

或定义自定义关闭:在lithium\data\Collection

$collection->sort(function ($a,$b) { 
    if ($a == $b) { 
     return 0; 
    } 
    return ($b > $a ? 1 : -1); 
}); 

检查文档,从中DocumentArray继承和lithium\util\CollectionCollection对象。

an Introduction to Collections by Joe Beeson。他不包括排序特别,但它值得一读(其他文章也)

+0

我试图在我的视图中进行排序它做到这一点:'$ thread-> postings-> sort('upvotes')'但它失败一个致命的错误:_Uncaught异常'BadMethodCallException'消息'没有模型绑定或未处理的方法调用'sort'。'在D:\ xampp \ htdocs \ AWF \ libraries \锂\数据\ Entity.php:191_你说的话对我来说听起来很合理,而且文档非常清晰,但我仍然无法调用此方法。我究竟做错了什么? – YMMD 2012-03-28 10:41:16

+0

我可以确认它运行正常后,运行您自己的代码https://github.com/UnionOfRAD/lithium/issues/405#issuecomment-4831856。确保没有任何事情干扰你的实体(在创建之前或之后等) – 2012-03-29 22:30:26

+0

现在,我将该方法的源代码手动复制到lithium \ util \ Collection.php中。我不知道为什么,但我的代码没有包含它,尽管我在19天前才下载了0.10版本。感谢您的帮助,并为提供这些难以捉摸的信息感到抱歉。 – YMMD 2012-03-30 12:23:36