Exemplo n.º 1
0
/**
 * Groups a collection by index returned by callback.
 *
 * @param Traversable|array $collection
 * @param callable $callback
 * @return array
 */
function group($collection, $callback)
{
    Exceptions\InvalidArgumentException::assertCollection($collection, __FUNCTION__, 1);
    Exceptions\InvalidArgumentException::assertCallback($callback, __FUNCTION__, 2);
    $groups = array();
    foreach ($collection as $index => $element) {
        $groupKey = call_user_func($callback, $element, $index, $collection);
        Exceptions\InvalidArgumentException::assertValidArrayKey($groupKey, __FUNCTION__);
        if (!isset($groups[$groupKey])) {
            $groups[$groupKey] = array();
        }
        $groups[$groupKey][$index] = $element;
    }
    return $groups;
}