I would love to sort an embedded MongoDB object using PHP Lithium. I have got a Model "Thread" which looks almost like this:
{
"_id": ObjectId("4f71bf4618b602580f000009"),
"postings": [
{text: "a", upvotes: 15, /*...*/},
{text: "b", upvotes: 23},
{text: "c", upvotes: 16},
{text: "d", upvotes: 42}
],
// bla
}
Now I would like to sort the postings depending on their upvotes. I already wrote a method which roughly does what I want:
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;
}
This works, but obviously it returns the postings as a plain array, while the unsorted postings were a lithium\data\collection\DocumentArray
type.
Do I really need to struggle with an array instead of an object or is there a way which allows me to sort them without losing the original data type?
A DocumentArray
object is a Collection
, and hopefully, Lithium Collections are sortable.
You can call sort()
on a $collection
different ways :
$collection->sort('field'); //sort naturally by the given field
Or define a custom closure :
$collection->sort(function ($a,$b) {
if ($a == $b) {
return 0;
}
return ($b > $a ? 1 : -1);
});
Check docs on lithium\data\Collection, from which DocumentArray
inherits, and lithium\util\Collection, the Collection
object.
an Introduction to Collections
by Joe Beeson. He don't cover sorting especially but it worth a read (other articles too)