collectionで使える関数combineを使うと新しいコレクションを簡単に作成できます。
例1
公式から抜粋した使用例です。
$items = [
['id' => 1, 'name' => 'foo', 'parent' => 'a'],
['id' => 2, 'name' => 'bar', 'parent' => 'b'],
['id' => 3, 'name' => 'baz', 'parent' => 'a'],
];
$combined = (new Collection($items))->combine('id', 'name');
// 配列に変換すると、結果は次のようになります。
[
1 => 'foo',
2 => 'bar',
3 => 'baz',
];
例2
配列を加工して新しい配列を作るときに便利です。下記はクライアント情報の配列から表示用の情報を抜き出した処理です。
$clients_view_list = collection($clients)
->map(
function ($client) {
return [
"k" => $client["name"],
"v" => [
"client_departments" => $client["client_departments"],
"representative" => $client["representative"],
],
];
}
)
->combine("k", "v");


