我喜欢使用PHP Lithium对嵌入式MongoDB对象进行排序。我有一个模型"Thread“,它看起来像这样:
{
"_id": ObjectId("4f71bf4618b602580f000009"),
"postings": [
{text: "a", upvotes: 15, /*...*/},
{text: "b", upvotes: 23},
{text: "c", upvotes: 16},
{text: "d", upvotes: 42}
],
// bla
}现在,我想根据他们的支持率对帖子进行排序。我已经写了一个方法,它大致可以做我想做的事情:
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类型。
我真的需要纠结于数组而不是对象吗?还是有一种方法可以让我在不丢失原始数据类型的情况下对它们进行排序?
发布于 2012-03-28 07:30:34
DocumentArray对象是一个Collection,希望Lithium Collections是可排序的。您可以通过不同的方式在$collection上调用sort():
$collection->sort('field'); //sort naturally by the given field或者定义一个自定义闭包:
$collection->sort(function ($a,$b) {
if ($a == $b) {
return 0;
}
return ($b > $a ? 1 : -1);
});查看DocumentArray继承自的lithium\data\Collection和Collection对象lithium\util\Collection上的文档。
乔·比森的an Introduction to Collections。他没有特别介绍排序,但它值得一读(其他文章也是如此)
https://stackoverflow.com/questions/9898179
复制相似问题