From: Andrey Kutejko Date: Tue, 22 Jul 2014 11:53:05 +0000 (+0300) Subject: group collection by property X-Git-Tag: 0.2~16 X-Git-Url: https://git.andy128k.dev/?a=commitdiff_plain;h=b920623e6d71750ec61da422cf6976ccb6f0941c;p=missing-tools.git group collection by property --- 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'])); + } }