]> git.andy128k.dev Git - missing-tools.git/commitdiff
group collection by property
authorAndrey Kutejko <andy128k@gmail.com>
Sun, 16 Feb 2014 09:03:13 +0000 (11:03 +0200)
committerAndrey Kutejko <andy128k@gmail.com>
Sun, 16 Feb 2014 09:03:13 +0000 (11:03 +0200)
src/collectiontools.php
t/CollectionTest.php

index fd62b2a26befc60269256866bbaa7286cb242816..2f87a9ccfe3933d6329a1f09b7933685265706ce 100644 (file)
@@ -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;
+    }
 }
 
index dcf952f3e9abc2a60a2f4646b6fbac368057a23e..daa5fb36f58feec4eae062102ae214f1029e977f 100644 (file)
@@ -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']));
+    }
 }