-
Notifications
You must be signed in to change notification settings - Fork 11.3k
[12.x] Added Arr::groupBy() helper function for array grouping #55472
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
By doing this, we would end up having |
@shaedrich, collections also have a https://laravel.com/docs/12.x/collections#method-groupby My guess is that @vishal2931 took inspiration from that implementation. |
Ah, thanks for the hint—nevermind 🤦🏻 |
$result = []; | ||
|
||
foreach ($array as $key => $item) { | ||
$groupKey = is_callable($groupBy) ? $groupBy($item, $key) : static::get($item, $groupBy); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I would ensure $groupBy
is a callback out the loop, so we don't need to check if it is a callback on every item.
Something like this:
$groupBy = is_callable($groupBy) ? $groupBy : fn ($item) => static::get($item, $groupBy);
foreach ($array as $key => $item) {
$groupKey = $groupBy($item, $key);
// ...
}
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks for the feedback, but that approach looks more readable than this one. 🤔
@rodrigopedra Correct. It will work same as Collection |
Yes you're right. I was thinking that instead of transforming it into a collection and then back to an array, we can do it directly on the array. What do you think? 🤔 |
Thanks for your pull request to Laravel! Unfortunately, I'm going to delay merging this code for now. To preserve our ability to adequately maintain the framework, we need to be very careful regarding the amount of code we include. If applicable, please consider releasing your code as a package so that the community can still take advantage of your contributions! |
Overview
This PR introduces a new
Arr::groupBy()
helper method to theIlluminate\Support\Arr
class. It provides a convenient way to group associative array by a specified key or a callback, with optional support for preserving the original array keys.Example