Skip to content

Instantly share code, notes, and snippets.

@KangYoosam
Created December 20, 2016 03:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KangYoosam/330e9539a8d2b7521c01b983c51fe708 to your computer and use it in GitHub Desktop.
Save KangYoosam/330e9539a8d2b7521c01b983c51fe708 to your computer and use it in GitHub Desktop.
[
[1, 4, 7],
[2, 5, 8],
[3, 6, 9],
]
[
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]
// 同じ名前のメソッドが存在しないかチェック
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);
});
}
// 必要な要素だけ取得
$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