From 044a18650f6a4778d5082b1e965af40b4532d207 Mon Sep 17 00:00:00 2001 From: Andrey Kutejko Date: Sun, 16 Feb 2014 11:03:13 +0200 Subject: [PATCH] group collection by property --- src/collectiontools.php | 10 ++++++++++ t/CollectionTest.php | 14 ++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/src/collectiontools.php b/src/collectiontools.php index fd62b2a..2f87a9c 100644 --- a/src/collectiontools.php +++ b/src/collectiontools.php @@ -56,5 +56,15 @@ final class Collections } return $result; } + + public static function groupByProperty($collection, $propertyName) + { + $groups = array(); + foreach ($collection as $item) { + $key = $item->$propertyName; + ArrayTools::pushToKey($groups, $key, $item); + } + return $groups; + } } diff --git a/t/CollectionTest.php b/t/CollectionTest.php index dcf952f..daa5fb3 100644 --- a/t/CollectionTest.php +++ b/t/CollectionTest.php @@ -44,5 +44,19 @@ class CollectionsTest 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 = Collections::groupByProperty($arr, 'color'); + $this->assertEquals(2, count($groups)); + $this->assertEquals(2, count($groups['red'])); + $this->assertEquals(2, count($groups['green'])); + } } -- 2.49.0