]> git.andy128k.dev Git - missing-tools.git/commitdiff
more groupBy methods
authorAndrey Kutejko <andy128k@gmail.com>
Sun, 16 Feb 2014 11:09:20 +0000 (13:09 +0200)
committerAndrey Kutejko <andy128k@gmail.com>
Sun, 16 Feb 2014 11:09:20 +0000 (13:09 +0200)
src/collectiontools.php

index 2f87a9ccfe3933d6329a1f09b7933685265706ce..92fd7f1d64a3b237379fa13f7914881b266937ee 100644 (file)
@@ -57,6 +57,14 @@ final class Collections
         return $result;
     }
 
+    public static function groupBy($collection, $key)
+    {
+        $groups = array();
+        foreach ($collection as $item)
+            ArrayTools::pushToKey($groups, call_user_func($key, $item), $item);
+        return $groups;
+    }
+
     public static function groupByProperty($collection, $propertyName)
     {
         $groups = array();
@@ -66,5 +74,20 @@ final class Collections
         }
         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);
+            ArrayTools::pushToKey($groups, $key, $item);
+        }
+        return $groups;
+    }
 }