I have a an instance of Laravel's Illuminate Collection. The array contains multiple properties.
I need to be able to sort the collection based on 2 different attributes.
I want to first sort by the attribute that is called "sort" and then by an attribute called "title".
Additionally, I have another collection that I like to sort it by the column "sort" if the value of sort is not null, then shuffle the items that have null for "sort" value.
How can I do this type of sort?
If you're using PHP 7, you can use the spaceship operator:
$collection->sort(function ($a, $b) {
return $a->sort === $b->sort ? $a->title <=> $b->title : $a->sort <=> $b->sort;
});
The <=>
symbol is called the spaceship operator (or technically: the combined comparison operator). You can read more about it in the RFC.
You can provide a callback function to Collection::sort
:
$collection->sort(function($a, $b) {
if($a->sort === $b->sort) {
if($a->title === $b->title) {
return 0;
}
return $a->title < $b->title ? -1 : 1;
}
return $a->sort < $b->sort ? -1 : 1;
});
This is documented here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With