Skip to content

Instantly share code, notes, and snippets.

@bran921007
Forked from sword-jin/transpose.php
Created October 15, 2020 11:51
Show Gist options
  • Save bran921007/006e6681c02dcab4e5e39ffb438d2c0d to your computer and use it in GitHub Desktop.
Save bran921007/006e6681c02dcab4e5e39ffb438d2c0d 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