-
-
Save bran921007/006e6681c02dcab4e5e39ffb438d2c0d to your computer and use it in GitHub Desktop.
Laravel collection transpose
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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