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

shiro_'s avatar

Calculate the sum of elements and list elements if have the same date

I have an array that looks like this:

Array
(
[0] => Array
    (
        [date] => 2015-07-07
        [payment_name] => Cash
    )

[1] => Array
    (
        [date] => 2015-07-10
        [payment_name] => Card
    )

[2] => Array
    (
        [date] => 2015-07-07
        [payment_name] => Mobile Money
    )

I am trying to calculate the sum of elements if they have the same date,as well as show all payment names that have the same date. For now, i have managed to display the calculated sum but i am having a hard time displaying the payment names as well. Only the first payment name comes with an undefined index. Any tips on how i can do this?

$requests = $builder->get(); 

        $aggregateArray = array();

        foreach($requests as $row) {
                if(!array_key_exists($row['date'], $aggregateArray)) {
                    $aggregateArray[$row['date']] = 0;
                }
                $aggregateArray[$row['date']] += $row['sales_count'];
                $aggregateArray[$row['payment_name']]; 
            } 

        return $aggregateArray;
0 likes
2 replies
jlrdw's avatar
jlrdw
Best Answer
Level 75

Where is the array coming from, if this data is in database, write a groupby query.

Or use collections which has a group by method. See the chapter on collections.

shiro_'s avatar

Let me try this, my array is multidimensional

Please or to participate in this conversation.