Skip to content

Instantly share code, notes, and snippets.

@sword-jin
Created April 11, 2016 10:33
Show Gist options
  • Save sword-jin/7f53003f0d054ca73da73dd8e6d5416f to your computer and use it in GitHub Desktop.
Save sword-jin/7f53003f0d054ca73da73dd8e6d5416f to your computer and use it in GitHub Desktop.
Laravel collection transpose
// key will be 0,1,2,...
Collection::macro('transpose', function() {
$items = array_map(function(...$items) {
return $items;
}, ...$this->values());
return new self($items);
});
// transpose(['name', 'email'])
Collection::macro('transpose', function($keys = null) {
$keys = $keys ?: range(0, $this->count() - 1);
$items = array_map(function(...$items) use ($keys) {
return array_combine($keys, $items);
}, ...$this->values());
return new self($items);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment