laravel / ideas

Issues board used for Laravel internals discussions.
938 stars 28 forks source link

Add collection mapWith method #2501

Open ajcastro opened 3 years ago

ajcastro commented 3 years ago

This is to have a way to use array_map with another sets of arrays/collections...

class Collection { 
...
public function mapWith(callable $callback, ...$arrays) 
{
  return new static(array_map($callback, $this->items, ...$arrays));
}
...
}
danilopolani commented 3 years ago

Is not enough to use the merge method on the collection?

collect(['first'])->merge(['second'])->map(...);
ajcastro commented 3 years ago

@danilopolani sorry about that, there are missing code in my example above and I edited it now..

Example use case is something like this:

array_map(function ($first_name, $last_name) {
  return "{$first_name} {$last_name}";
}, $first_names, $last_names);

or

collect($first_names)->mapWith(function ($first_name, $last_name, $age) {
  return "{$first_name} {$last_name}, {$age}";
}, $last_names, $ages);

Also

$rows = collect([
// ... generate rows to insert in a table
]);
$uuids = get_uuids($rows->count()); // this returns a number of uuids equal to the number of rows

$rows = $rows->mapWith(function($row, $uuid) {
  $row['id'] = $uuid;
  return $row;
}, $uuids);

DB::table(...)->insert($rows);