Skip to content
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

[8.x] Add missing sortByMany method to Arr helper #35277

Merged
merged 3 commits into from Nov 19, 2020
Merged

[8.x] Add missing sortByMany method to Arr helper #35277

merged 3 commits into from Nov 19, 2020

Conversation

johnylemon
Copy link
Contributor

The need to sort array with multiple columns is the problem I faced so many times. Incuding today.
Arr and Str helpers are really powerfull and cover so many common use cases. But not this one.
This PR fills this gap, empowering helpers functionality.

Sorting may be done by array of strings:

$sorted = Arr::sortByMany($unsorted, [
    'name', 'age'
];

These props will be sorted in ascending order by default.

Order may be changed, using array instead of property name:

$sorted = Arr::sortByMany($unsorted, [
    ['name', false], // will be ordered by `name` descending  
    ['age', true] // then by age ascending, if there are items with same `name` value
];

Sometimes more complicated logic or calling object methods is needed, this may be achieved using anonymous functions:

$sorted = Arr::sortByMany($unsorted, [
    // order by childrens count asc
    function($a, $b) {
        return $a->childrens()->count() <=> $b->childrens()->count();
    },
    // then by grandchildrens by descending order if needed
    function($a, $b) {
        return $b->grandchildrens()->count() <=> $a->grandchildrens()->count();
    }
];

When using anonymous functions, order boolean parameter won't be respected.

@johnylemon johnylemon changed the title Add missing sortByMany method to Arr helper [8.x] Add missing sortByMany method to Arr helper Nov 18, 2020
@taylorotwell taylorotwell merged commit 174c0e5 into laravel:8.x Nov 19, 2020
@taylorotwell
Copy link
Member

You can just pass an array to Arr::sort or Collection::sortBy now. Thanks.

@taylorotwell
Copy link
Member

Screen Shot 2020-11-19 at 9 27 45 AM

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

3 participants