Created
April 11, 2016 10:33
-
-
Save sword-jin/7f53003f0d054ca73da73dd8e6d5416f 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