Rahul W
Rahul W

Reputation: 193

How to sum array values and add total at the end in the same array

Good Afternoon,

Hello, i am new to coding and Laravel and working on home project as a self leaner. i stuck at array sum where i want to make the sum of values in array and add the same sum at the end of tjat array itself.

array:7 [▼
"2022-12-04" => array:9 [▼
"startdate" => "2022-12-04"
"Stotalbmilk" => "29.00"
"Stotala2milk" => "22.50"
"Stotaljmilk" => "20.00"
"Stotalmilk" => "71.50"
"Dtotalbmilk" => "40.00"
"Dtotala2milk" => "0.00"
"Dtotaljmilk" => "0.00"
"Dtotalmilk" => "40.00"
]

in the above array i am to add "TOTAL" at he bottom which value will be addition of 2 values ( "Stotalmilk" and "Dtotalmilk" ). Expected array will be

 array:7 [▼
"2022-12-04" => array:9 [▼
"startdate" => "2022-12-04"
"Stotalbmilk" => "29.00"
"Stotala2milk" => "22.50"
"Stotaljmilk" => "20.00"
**"Stotalmilk" => "71.50"**
"Dtotalbmilk" => "40.00"
"Dtotala2milk" => "0.00"
"Dtotaljmilk" => "0.00"
**"Dtotalmilk" => "40.00"**
**"TOTAL" => "111.50"**
]

hope i properly explain my question and sorry for poor english. Thanks in advance

Upvotes: -1

Views: 224

Answers (1)

RossTsachev
RossTsachev

Reputation: 921

So if your array have many dates with data, you can do something like:

$result = [];

foreach ($array as $date => $amounts) {
    $total = (float) $amounts['Stotalmilk'] + (float) $amounts['Dtotalmilk'];
    $amounts['TOTAL'] = number_format($total, 2, '.');
    $result[$date] = $amounts;
}

Upvotes: 1

Related Questions