From dee17de06baa84532a211ba2d920629e1c2f938e Mon Sep 17 00:00:00 2001 From: Andrey Kutejko Date: Sun, 16 Feb 2014 13:09:20 +0200 Subject: [PATCH] more groupBy methods --- src/collectiontools.php | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/src/collectiontools.php b/src/collectiontools.php index 2f87a9c..92fd7f1 100644 --- a/src/collectiontools.php +++ b/src/collectiontools.php @@ -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; + } } -- 2.49.0