]> git.andy128k.dev Git - missing-tools.git/commitdiff
more groupBy methods
authorAndrey Kutejko <andy128k@gmail.com>
Tue, 22 Jul 2014 11:53:58 +0000 (14:53 +0300)
committerAndrey Kutejko <andy128k@gmail.com>
Tue, 22 Jul 2014 11:53:58 +0000 (14:53 +0300)
src/collection.php

index 87332ee140bc33890f4f08338076530964c71591..d9b39ae10dd5a6d670bd5f2e66559117d833a71c 100644 (file)
@@ -59,6 +59,14 @@ final class Collection
         return $result;
     }
 
+    public static function groupBy($collection, $key)
+    {
+        $groups = array();
+        foreach ($collection as $item)
+            Arr::pushToKey($groups, call_user_func($key, $item), $item);
+        return $groups;
+    }
+
     public static function groupByProperty($collection, $propertyName)
     {
         $groups = array();
@@ -68,5 +76,20 @@ final class Collection
         }
         return $groups;
     }
+
+    public static function groupByMethod(/*$collection, $methodName, ...$args*/)
+    {
+        $args = func_get_args();
+        $collection = $args[0];
+        $methodName = $args[1];
+        $methodArgs = array_slice($args, 2);
+
+        $groups = array();
+        foreach ($collection as $item) {
+            $key = call_user_func_array(array($item, $methodName), $methodArgs);
+            Arr::pushToKey($groups, $key, $item);
+        }
+        return $groups;
+    }
 }