【Laravel】 Laravel 5.7コレクション を一気に勉強(9) − make,map,mapInto,mapSpread,mapToGroups




この記事は最終更新日から2年以上経過しています。

make()

新しいコレクションインスタンスを生成します。

dump(Collection::make([0, 1, 2])->all());
/*
array:3 [▼
  0 => 0
  1 => 1
  2 => 2
]
*/

map()

コレクションのキー・値をコールバックに渡し、新しいコレクションを生成します。

$array = [];
for($i = 0; $i < 6; $i++) {
    $array[] = $i;
}
$collection = collect($array)->map(function($item, $key) {
    return $key % 2 ? $key : null;
});
dump($collection->all());
/*
array:6 [▼
  0 => null
  1 => 1
  2 => null
  3 => 3
  4 => null
  5 => 5
]
*/

mapInto()

パラメーターで指定したクラスのコンストラクタに値を渡し、各インスタンスを格納したコレクションを生成します。

class MyUrl
{
    private $params;

    public function __construct($params)
    {
        $this->params = $params;
    }
}
$collection = collect(['demo/collection/index05', 'demo/collection/index06', 'demo/collection/index07']);
$urlCollection = $collection->mapInto(MyUrl::class);
dump($urlCollection->all());
/*
array:3 [▼
  0 => MyUrl {#426 ▼
    -params: "demo/collection/index05"
  }
  1 => MyUrl {#429 ▼
    -params: "demo/collection/index06"
  }
  2 => MyUrl {#425 ▼
    -params: "demo/collection/index07"
  }
]
*/

mapSpread()

指定したコールバックに多次元配列の値を渡し、処理した結果を格納した新しいコレクションを生成します。

$array = [];
for($i = 0; $i < 10; $i++) {
    $array[] = $i;
}
$collection = collect($array)->chunk(3);
dump($collection->mapSpread(function(...$params) {
    return $params[0] * $params[count($params) - 1];
})->all());
/*
array:4 [▼
  0 => 0
  1 => 3
  2 => 12
  3 => 27
]
*/

mapToGroups()

パラメーターに指定したコールバックが返すキーと値でグルーピングします。

$collection = collect([
    ['name' => 'ichiro', 'no' => 51, 'team' => 'B'],
    ['name' => 'ichiro', 'no' => 31, 'team' => 'NY'],
    ['name' => 'matsui', 'no' => 55, 'team' => 'G'],
    ['name' => 'senichi', 'no' => 77, 'team' => 'D'],
]);
dump($collection->mapToGroups(function($item, $key) {
    return [$item['name'] => $item['team']];
}));
/*
array:3 [▼
  "ichiro" => Collection {#436 ▼
    #items: array:2 [▼
      0 => "B"
      1 => "NY"
    ]
  }
  "matsui" => Collection {#437 ▼
    #items: array:1 [▼
      0 => "G"
    ]
  }
  "senichi" => Collection {#432 ▼
    #items: array:1 [▼
      0 => "D"
    ]
  }
]
*/