Collection::group PHP Метод

group() публичный Метод

Groups the collection by a given callback
public group ( callable $callback ) : object
$callback callable
Результат object A new collection with an item for each group and a subcollection in each group
    public function group($callback)
    {
        if (!is_callable($callback)) {
            throw new Exception($callback . ' is not callable. Did you mean to use groupBy()?');
        }
        $groups = array();
        foreach ($this->data as $key => $item) {
            // get the value to group by
            $value = call_user_func($callback, $item);
            // make sure that there's always a proper value to group by
            if (!$value) {
                throw new Exception('Invalid grouping value for key: ' . $key);
            }
            // make sure we have a proper key for each group
            if (is_array($value)) {
                throw new Exception('You cannot group by arrays or objects');
            } else {
                if (is_object($value)) {
                    if (!method_exists($value, '__toString')) {
                        throw new Exception('You cannot group by arrays or objects');
                    } else {
                        $value = (string) $value;
                    }
                }
            }
            if (!isset($groups[$value])) {
                // create a new entry for the group if it does not exist yet
                $groups[$value] = new static(array($key => $item));
            } else {
                // add the item to an existing group
                $groups[$value]->set($key, $item);
            }
        }
        return new Collection($groups);
    }

Usage Example

Пример #1
0
 public function testGroup()
 {
     $collection = new Collection();
     $collection->user1 = array('username' => 'peter', 'group' => 'admin');
     $collection->user2 = array('username' => 'paul', 'group' => 'admin');
     $collection->user3 = array('username' => 'mary', 'group' => 'client');
     $groups = $collection->group(function ($item) {
         return $item['group'];
     });
     $this->assertEquals(2, $groups->admin()->count());
     $this->assertEquals(1, $groups->client()->count());
     $firstAdmin = $groups->admin()->first();
     $this->assertEquals('peter', $firstAdmin['username']);
 }
All Usage Examples Of Collection::group