Skip to content

Instantly share code, notes, and snippets.

@pionl
Created December 15, 2015 09:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pionl/84887c633057f08bc9a6 to your computer and use it in GitHub Desktop.
Save pionl/84887c633057f08bc9a6 to your computer and use it in GitHub Desktop.
<?php
namespace Pion\Support;
use Illuminate\Support\Collection;
/**
* Class GroupedCollection
*
* Collection that will support adding values with grouped index (collection indexed by groupKey)
*
* @package Pion\Support
*/
class GroupedCollection extends Collection
{
/**
* Adds the grouped collection
*
* @param mixed $groupKey
* @param mixed $value
* @param mixed|null $key
*
* @return $this
*/
public function add($groupKey, $value, $key = null)
{
// get the group, if the group is not created
// null will be returned
$group = $this->get($groupKey);
// create new empty group
if (is_null($group)) {
$group = new Collection();
$this->put($groupKey, $group);
}
// add the value to the collection
$group->put($key, $value);
return $this;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment