Created
December 20, 2016 03:16
-
-
Save KangYoosam/330e9539a8d2b7521c01b983c51fe708 to your computer and use it in GitHub Desktop.
Laravelでtranspose ref: http://qiita.com/kangyoosam/items/f5c4514ad34d9a5c201c
This file contains 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
[ | |
[1, 4, 7], | |
[2, 5, 8], | |
[3, 6, 9], | |
] |
This file contains 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
[ | |
[1, 2, 3], | |
[4, 5, 6], | |
[7, 8, 9], | |
] |
This file contains 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
// 同じ名前のメソッドが存在しないかチェック | |
if (! Collection::hasMacro('transpose')) { | |
/* | |
* Transpose an array. | |
* | |
* @return \Illuminate\Support\Collection | |
*/ | |
Collection::macro('transpose', function () { | |
$items = array_map(function (...$items) { | |
return $items; | |
}, ...$this->values()); | |
return new static($items); | |
}); | |
} |
This file contains 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
// 必要な要素だけ取得 | |
$before = collect($input_data)->only('name', 'email', 'address'); | |
// transpose実行 | |
$after = $before->transpose()->map(function ($data) { | |
return [ | |
'name' => $data['0'], | |
'email' => $data['1'], | |
'address' => $data['2'], | |
]; | |
}); | |
// transpose前 | |
dd($before); | |
// [ | |
// ['田中', '鈴木', '佐藤'], | |
// ['aaa@example.com', 'bbb@example.com', 'ccc@example.com'], | |
// ['東京', '大阪','福岡'], | |
// ]; | |
// transpose後 | |
dd($after); | |
// [ | |
// ['田中', 'aaa@example.com', '東京'], | |
// ['鈴木', 'bbb@example.com', '大阪'], | |
// ['佐藤', 'ccc@example.com','福岡'], | |
// ]; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment