Skip to content

Commit 1a2b767

Browse files
Merge branch '8.x'
2 parents 47babf6 + 8d96c94 commit 1a2b767

File tree

2 files changed

+50
-2
lines changed

2 files changed

+50
-2
lines changed

Arr.php

+1-1
Original file line numberDiff line numberDiff line change
@@ -604,7 +604,7 @@ public static function shuffle($array, $seed = null)
604604
* Sort the array using the given callback or "dot" notation.
605605
*
606606
* @param array $array
607-
* @param callable|string|null $callback
607+
* @param callable|array|string|null $callback
608608
* @return array
609609
*/
610610
public static function sort($array, $callback = null)

Collection.php

+49-1
Original file line numberDiff line numberDiff line change
@@ -1110,13 +1110,17 @@ public function sortDesc($options = SORT_REGULAR)
11101110
/**
11111111
* Sort the collection using the given callback.
11121112
*
1113-
* @param callable|string $callback
1113+
* @param callable|array|string $callback
11141114
* @param int $options
11151115
* @param bool $descending
11161116
* @return static
11171117
*/
11181118
public function sortBy($callback, $options = SORT_REGULAR, $descending = false)
11191119
{
1120+
if (is_array($callback)) {
1121+
return $this->sortByMany($callback);
1122+
}
1123+
11201124
$results = [];
11211125

11221126
$callback = $this->valueRetriever($callback);
@@ -1141,6 +1145,50 @@ public function sortBy($callback, $options = SORT_REGULAR, $descending = false)
11411145
return new static($results);
11421146
}
11431147

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+
11441192
/**
11451193
* Sort the collection in descending order using the given callback.
11461194
*

0 commit comments

Comments
 (0)