diff --git a/src/Illuminate/Support/Collection.php b/src/Illuminate/Support/Collection.php index 63acd685839b..57cfee9aee38 100644 --- a/src/Illuminate/Support/Collection.php +++ b/src/Illuminate/Support/Collection.php @@ -920,6 +920,23 @@ public function slice($offset, $length = null) return new static(array_slice($this->items, $offset, $length, true)); } + /** + * Split a collection into a certain number of groups. + * + * @param int $numberOfGroups + * @return static + */ + public function split($numberOfGroups) + { + if ($this->isEmpty()) { + return new static; + } + + $groupSize = ceil($this->count() / $numberOfGroups); + + return $this->chunk($groupSize); + } + /** * Chunk the underlying collection array. * diff --git a/tests/Support/SupportCollectionTest.php b/tests/Support/SupportCollectionTest.php index 89a878753224..9c069cc7745c 100755 --- a/tests/Support/SupportCollectionTest.php +++ b/tests/Support/SupportCollectionTest.php @@ -1554,6 +1554,54 @@ public function testCollectonFromTraversableWithKeys() $collection = new Collection(new \ArrayObject(['foo' => 1, 'bar' => 2, 'baz' => 3])); $this->assertEquals(['foo' => 1, 'bar' => 2, 'baz' => 3], $collection->toArray()); } + + public function testSplitCollectionWithADivisableCount() + { + $collection = new Collection(['a', 'b', 'c', 'd']); + + $this->assertEquals( + [['a', 'b'], ['c', 'd']], + $collection->split(2)->map(function (Collection $chunk) { + return $chunk->values()->toArray(); + })->toArray() + ); + } + + public function testSplitCollectionWithAnUndivisableCount() + { + $collection = new Collection(['a', 'b', 'c']); + + $this->assertEquals( + [['a', 'b'], ['c']], + $collection->split(2)->map(function (Collection $chunk) { + return $chunk->values()->toArray(); + })->toArray() + ); + } + + public function testSplitCollectionWithCountLessThenDivisor() + { + $collection = new Collection(['a']); + + $this->assertEquals( + [['a']], + $collection->split(2)->map(function (Collection $chunk) { + return $chunk->values()->toArray(); + })->toArray() + ); + } + + public function testSplitEmptyCollection() + { + $collection = new Collection(); + + $this->assertEquals( + [], + $collection->split(2)->map(function (Collection $chunk) { + return $chunk->values()->toArray(); + })->toArray() + ); + } } class TestAccessorEloquentTestStub