📅  最后修改于: 2023-12-03 15:32:33.061000             🧑  作者: Mango
If you are working with Laravel and need to shuffle a collection, you can use the built-in shuffle()
method. This method can be used to randomly re-arrange the items in a collection.
$collection->shuffle();
The shuffle()
method doesn't accept any arguments, it simply randomizes the order of the items in the collection.
use Illuminate\Support\Collection;
$collection = collect([1, 2, 3, 4, 5, 6]);
$shuffled = $collection->shuffle();
$shuffled->all();
This will output something like:
array:6 [
3 => 4
0 => 1
1 => 2
4 => 5
2 => 3
5 => 6
]
As you can see, the order of the items in the collection has been randomized.
The shuffle()
method can be useful in situations where you need to randomize the order of a collection's items. It is also an easy method to use, with no arguments to pass.
I hope you found this helpful!