Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ericknyoto's avatar

Which Collection method can be used for this array?

I have a method like this

foreach ($data as $datum) {
            $detail = [
                'product_id' => $datum->product_id,
                'total' => $datum->total,
                'date' => $datum->date,
                'total_surface' => $datum->total_surface,
                'batch' => $datum->batch,
            ];
            $result[] = $detail;
}

 return $result;

What are the Collection method that can be used to transform array of data like example above? I've searched from the documentation for map, mapToGroups, mapWithKeys, but the example isn't like what I need. Or I looking at the wrong method (map)?

Thanks before.

0 likes
1 reply
Tray2's avatar
Tray2
Best Answer
Level 73

Since you are just looping over it, then you should use map, but there is nothing really wrong with a classic foreach.

It does look just like you are converting an eloquent collection to an array.

If so just use the toArray method.

return $data->toArray();

If that is not the case you could make it a little cleaner.

function whatever($data)
{
  $result = [];
  foreach ($data as $datum) {
    $result[] = [
     'product_id' => $datum->product_id,
     'total' => $datum->total,
     'date' => $datum->date,
     'total_surface' => $datum->total_surface,
     'batch' => $datum->batch,
    ];
  }
  return $result;
}
1 like

Please or to participate in this conversation.