diff --git a/src/Illuminate/Support/Collection.php b/src/Illuminate/Support/Collection.php index 6ae2c7a4919d..2bbca6ff29d4 100644 --- a/src/Illuminate/Support/Collection.php +++ b/src/Illuminate/Support/Collection.php @@ -1475,6 +1475,33 @@ public function sortByDesc($callback, $options = SORT_REGULAR) return $this->sortBy($callback, $options, true); } + /** + * Sort the collection keys. + * + * @param int $options + * @param bool $descending + * @return static + */ + public function sortKeys($options = SORT_REGULAR, $descending = false) + { + $items = $this->items; + + $descending ? krsort($items, $options) : ksort($items, $options); + + return new static($items); + } + + /** + * Sort the collection keys in descending order. + * + * @param int $options + * @return static + */ + public function sortKeysDesc($options = SORT_REGULAR) + { + return $this->sortKeys($options, true); + } + /** * Splice a portion of the underlying collection array. * diff --git a/tests/Support/SupportCollectionTest.php b/tests/Support/SupportCollectionTest.php index 1936cbe05016..b3c21537fb77 100755 --- a/tests/Support/SupportCollectionTest.php +++ b/tests/Support/SupportCollectionTest.php @@ -943,6 +943,20 @@ public function testSortByAlwaysReturnsAssoc() $this->assertEquals([1 => 'dayle', 0 => 'taylor'], $data->all()); } + public function testSortKeys() + { + $data = new Collection(['b' => 'dayle', 'a' => 'taylor']); + + $this->assertEquals(['a' => 'taylor', 'b' => 'dayle'], $data->sortKeys()->all()); + } + + public function testSortKeysDesc() + { + $data = new Collection(['a' => 'taylor', 'b' => 'dayle']); + + $this->assertEquals(['b' => 'dayle', 'a' => 'taylor'], $data->sortKeys()->all()); + } + public function testReverse() { $data = new Collection(['zaeed', 'alan']);