From: Andrey Kutejko Date: Sun, 16 Feb 2014 09:03:13 +0000 (+0200) Subject: group collection by property X-Git-Tag: 0.1~2 X-Git-Url: https://git.andy128k.dev/?a=commitdiff_plain;h=044a18650f6a4778d5082b1e965af40b4532d207;p=missing-tools.git group collection by property --- 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'])); + } }