@@ -1110,13 +1110,17 @@ public function sortDesc($options = SORT_REGULAR)
1110
1110
/**
1111
1111
* Sort the collection using the given callback.
1112
1112
*
1113
- * @param callable|string $callback
1113
+ * @param callable|array| string $callback
1114
1114
* @param int $options
1115
1115
* @param bool $descending
1116
1116
* @return static
1117
1117
*/
1118
1118
public function sortBy ($ callback , $ options = SORT_REGULAR , $ descending = false )
1119
1119
{
1120
+ if (is_array ($ callback )) {
1121
+ return $ this ->sortByMany ($ callback );
1122
+ }
1123
+
1120
1124
$ results = [];
1121
1125
1122
1126
$ callback = $ this ->valueRetriever ($ callback );
@@ -1141,6 +1145,50 @@ public function sortBy($callback, $options = SORT_REGULAR, $descending = false)
1141
1145
return new static ($ results );
1142
1146
}
1143
1147
1148
+ /**
1149
+ * Sort the collection using multiple comparisons.
1150
+ *
1151
+ * @param array $comparisons
1152
+ * @return static
1153
+ */
1154
+ protected function sortByMany (array $ comparisons = [])
1155
+ {
1156
+ $ items = $ this ->items ;
1157
+
1158
+ usort ($ items , function ($ a , $ b ) use ($ comparisons ) {
1159
+ foreach ($ comparisons as $ comparison ) {
1160
+ $ comparison = Arr::wrap ($ comparison );
1161
+
1162
+ $ prop = $ comparison [0 ];
1163
+
1164
+ $ ascending = Arr::get ($ comparison , 1 , true ) === true ||
1165
+ Arr::get ($ comparison , 1 , true ) === 'asc ' ;
1166
+
1167
+ $ result = 0 ;
1168
+
1169
+ if (is_callable ($ prop )) {
1170
+ $ result = $ prop ($ a , $ b );
1171
+ } else {
1172
+ $ values = [Arr::get ($ a , $ prop ), Arr::get ($ b , $ prop )];
1173
+
1174
+ if (! $ ascending ) {
1175
+ $ values = array_reverse ($ values );
1176
+ }
1177
+
1178
+ $ result = $ values [0 ] <=> $ values [1 ];
1179
+ }
1180
+
1181
+ if ($ result === 0 ) {
1182
+ continue ;
1183
+ }
1184
+
1185
+ return $ result ;
1186
+ }
1187
+ });
1188
+
1189
+ return new static ($ items );
1190
+ }
1191
+
1144
1192
/**
1145
1193
* Sort the collection in descending order using the given callback.
1146
1194
*
0 commit comments