From b920623e6d71750ec61da422cf6976ccb6f0941c Mon Sep 17 00:00:00 2001 From: Andrey Kutejko Date: Tue, 22 Jul 2014 14:53:05 +0300 Subject: [PATCH] group collection by property --- src/collection.php | 10 ++++++++++ t/CollectionTest.php | 14 ++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/src/collection.php b/src/collection.php index 9c51f9b..87332ee 100644 --- a/src/collection.php +++ b/src/collection.php @@ -58,5 +58,15 @@ final class Collection } return $result; } + + public static function groupByProperty($collection, $propertyName) + { + $groups = array(); + foreach ($collection as $item) { + $key = $item->$propertyName; + Arr::pushToKey($groups, $key, $item); + } + return $groups; + } } diff --git a/t/CollectionTest.php b/t/CollectionTest.php index 4005b03..a1c505e 100644 --- a/t/CollectionTest.php +++ b/t/CollectionTest.php @@ -44,5 +44,19 @@ class CollectionTest extends PHPUnit_Framework_TestCase $this->assertEquals(3, count($chunks[0])); $this->assertEquals(3, count($chunks[1])); } + + public function testGroupByProperty() + { + $arr = array( + (object)array('name' => 'apple', 'color' => 'green'), + (object)array('name' => 'carrot', 'color' => 'red'), + (object)array('name' => 'tomato', 'color' => 'red'), + (object)array('name' => 'grapefruit', 'color' => 'green'), + ); + $groups = \PFF\Collection::groupByProperty($arr, 'color'); + $this->assertEquals(2, count($groups)); + $this->assertEquals(2, count($groups['red'])); + $this->assertEquals(2, count($groups['green'])); + } } -- 2.49.0