I have a database search that returns thousands of entries which I then group by two columns like so:
$results = $merged->groupBy(['source', 'parent']);
The result is Laravel Collection with the following structure, grouped first by the 'source' (1_k12_fill_trypsin_dig
), then the 'parent' (2, 4, 9, 10...
), and each 'parent' has some number of children:
I want to sort the parents by the number of children they have. So, in this example, I would want '4' to be at the top, so that the child count serves as the 'truth test' in some closure. I just don't know how to access these elements. I was hoping to use Collection methods as opposed to looping through with vanilla PHP.
My Answer:
You can achieve this by using the `sortByDesc` method on the Laravel Collection. Here's an example of how you can sort the parents by the number of children they have:
php
$results = $merged->groupBy(['source', 'parent']);
$results->transform(function ($item) {
return $item->sortByDesc('child_count')->values();
});
$results = $results->sortByDesc(function ($item) {
return $item->count();
});
// Now $results will be sorted by the number of children each parent has
In this example, we first use the `transform` method to sort each group of children by the 'child_count' in descending order. Then, we use the `sortByDesc` method on the entire Collection to sort the parents by the number of children they have.
Rate this post
4 of 5 based on 7507 votesComments