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

vincej's avatar
Level 15

Like some suggestions on how best to sum a series of values in a collection

Ok, so the end goal is to export data out of my DB as an xls. Great, I have all that working nicely. But it is just the RAW data. Not nice. I need strategy to sum the values for a series of repeating ID's. Here is the meat of the problem. Note - this is only test data.

ID	Name	Date	          Time In	Time Out     Time
1	Daniel	2020-10-23	15:06:48	15:09:01	2
1	Daniel	2020-10-27	14:57:36	15:04:34	7
2	Thomas	2020-10-27	14:57:38	15:04:36	7
2	Thomas	2020-10-23	15:11:58	15:15:21	3
3	Peter	2020-10-23	15:13:01	15:18:19	5
3	Peter	2020-10-27	14:57:40	15:04:37	7
4	Nancy	2020-10-23	15:15:00	15:19:00	4
4	Nancy	2020-10-27	14:57:41	15:04:38	7

What we have here is a bunch of children who come into school everyday. For each day, their arrival and departure time is noted, and the length of their stay is calculated and stored by day. At the end of the month, an aggragate report for the whole month must be produced. So, for October, Daniel had N hours total. Thomas had Y hours total, etc etc. That report will then be downloadable using Laravel excel.

I thought of using a complex foreach, but then realised that as the raw data is a Laravel collection, there may be a better way.

Any / All suggestions gratefully received !!

0 likes
2 replies
jjoek's avatar

Talking of collections: https://laravel.com/docs/8.x/collections#method-sum

Maybe this is what you looking for: `

    $collection = collect([
        ['name' => 'Chair', 'colors' => ['Black']],
        ['name' => 'Desk', 'colors' => ['Black', 'Mahogany']],
        ['name' => 'Bookcase', 'colors' => ['Red', 'Beige', 'Brown']],
    ]);

    $collection->sum(function ($product) {
        return count($product['colors']);
    });

`

Please or to participate in this conversation.