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
DocumentArrayobject is aCollection, and hopefully, Lithium Collections are sortable.You can call
sort()on a$collectiondifferent ways :Or define a custom closure :
Check docs on lithium\data\Collection, from which
DocumentArrayinherits, and lithium\util\Collection, theCollectionobject.an Introduction to
Collectionsby Joe Beeson. He don’t cover sorting especially but it worth a read (other articles too)