In Illuminate/Collections, you can use the groupBy()
function to group elements in a collection by a specific key. Here's an example:
use Illuminate\Support\Collection;
$collection = new Collection([
['name' => 'John', 'age' => 28],
['name' => 'Jane', 'age' => 32],
['name' => 'Adam', 'age' => 28],
]);
$grouped = $collection->groupBy('age');
$grouped->each(function ($items, $age) {
echo "People with age $age:\n";
foreach ($items as $item) {
echo "- {$item['name']}\n";
}
echo "\n";
});
This will output:
People with age 28:
- John
- Adam
People with age 32:
- Jane
In the example, the groupBy('age')
method is called on the collection, which groups the elements by the 'age' key. The resulting grouped collection assigns each unique 'age' value as the keys, with the corresponding elements as the values. The each
method is then used to iterate over each group and print out the details.