]> git.andy128k.dev Git - missing-tools.git/commitdiff
group collection by property
authorAndrey Kutejko <andy128k@gmail.com>
Tue, 22 Jul 2014 11:53:05 +0000 (14:53 +0300)
committerAndrey Kutejko <andy128k@gmail.com>
Tue, 22 Jul 2014 11:53:05 +0000 (14:53 +0300)
src/collection.php
t/CollectionTest.php

index 9c51f9bf80d833e55b7cc24933a8b1f6b15e0c0b..87332ee140bc33890f4f08338076530964c71591 100644 (file)
@@ -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;
+    }
 }
 
index 4005b03a91d9c343f2f0663af0de4fcb6937fd2f..a1c505e3294a6da6e77f9ffdb94cb83a13b5ca7a 100644 (file)
@@ -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']));
+    }
 }