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.
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
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;
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.
Please or to participate in this conversation.