Collection::groupBy PHP Method

groupBy() public method

Groups the collection by a given field
public groupBy ( string $field, $i = true ) : object
$field string
return object A new collection with an item for each group and a subcollection in each group
    public function groupBy($field, $i = true)
    {
        if (!is_string($field)) {
            throw new Exception('Cannot group by non-string values. Did you mean to call group()?');
        }
        return $this->group(function ($item) use($field, $i) {
            $value = $this->extractValue($item, $field);
            // ignore upper/lowercase for group names
            return $i == true ? str::lower($value) : $value;
        });
    }

Usage Example

 public function testGroupBy()
 {
     $collection = new Collection(['first' => new Bar('a'), 'third' => new Bar('c'), 'fourth' => new Bar('c'), 'second' => new Bar('b')]);
     $collections = $collection->groupBy(function (Bar $bar) {
         return $bar->foo;
     });
     $this->assertCount(3, $collections);
     $this->assertSame($collection['first'], $collections['a']['first']);
     $this->assertSame($collection['second'], $collections['b']['second']);
     $this->assertSame($collection['third'], $collections['c']['third']);
     $this->assertSame($collection['fourth'], $collections['c']['fourth']);
 }
All Usage Examples Of Collection::groupBy