Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jarektkaczyk/e1769a7290ae9d2c3390 to your computer and use it in GitHub Desktop.
Save jarektkaczyk/e1769a7290ae9d2c3390 to your computer and use it in GitHub Desktop.
Laravel 5 - how to sort collection by multiple integer fields
<?php
>>> $col = collect(json_decode(json_encode([['id' => 1,'bool' => 0, 'count' => 15], ['id' => 2, 'bool' => 1, 'count' => 20], ['id' => 3, 'bool' => 0, 'count' => 10], ['id' => 4, 'bool' => 1, 'count' => 16]])))
=> Illuminate\Support\Collection {#935
all: [
{#936
+"id": 1
+"bool": 0
+"count": 15
}
{#934
+"id": 2
+"bool": 1
+"count": 20
}
{#884
+"id": 3
+"bool": 0
+"count": 10
}
{#894
+"id": 4
+"bool": 1
+"count": 16
}
]
}
// Use sensible integer that will exceed $item->count, I'm using 1 000 000
>>> // bool asc, count asc
>>> $col->sortBy(function ($item) { return $item->bool * 1000000 + $item->count; })
=> Illuminate\Support\Collection {#844
all: [
2 => {#884
+"id": 3
+"bool": 0
+"count": 10
}
0 => {#936
+"id": 1
+"bool": 0
+"count": 15
}
3 => {#894
+"id": 4
+"bool": 1
+"count": 16
}
1 => {#934
+"id": 2
+"bool": 1
+"count": 20
}
]
}
>>> // bool asc, count desc
>>> $col->sortBy(function ($item) { return $item->bool * 1000000 - $item->count; })
=> Illuminate\Support\Collection {#710
all: [
0 => {#936
+"id": 1
+"bool": 0
+"count": 15
}
2 => {#884
+"id": 3
+"bool": 0
+"count": 10
}
1 => {#934
+"id": 2
+"bool": 1
+"count": 20
}
3 => {#894
+"id": 4
+"bool": 1
+"count": 16
}
]
}
>>> // bool desc, count desc
>>> $col->sortBy(function ($item) { return $item->bool * -1000000 - $item->count; })
=> Illuminate\Support\Collection {#860
all: [
1 => {#934
+"id": 2
+"bool": 1
+"count": 20
}
3 => {#894
+"id": 4
+"bool": 1
+"count": 16
}
0 => {#936
+"id": 1
+"bool": 0
+"count": 15
}
2 => {#884
+"id": 3
+"bool": 0
+"count": 10
}
]
}
>>> // bool desc, count asc
>>> $col->sortBy(function ($item) { return $item->bool * -1000000 + $item->count; })
=> Illuminate\Support\Collection {#841
all: [
3 => {#894
+"id": 4
+"bool": 1
+"count": 16
}
1 => {#934
+"id": 2
+"bool": 1
+"count": 20
}
2 => {#884
+"id": 3
+"bool": 0
+"count": 10
}
0 => {#936
+"id": 1
+"bool": 0
+"count": 15
}
]
}
@tswonke
Copy link

tswonke commented Jan 6, 2016

Great solution, thank you!

@Gummibeer
Copy link

Really great helper! 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment