I need help to sum values in an array. The array is called $results and I need to sum the Total_Sales values for each Month. EDIT - I have the loop below that I need to get the results; however I get notices. How can I improve the code so that I don't get those notices?
Here's the array:
$results
array(4) {
[0]=>
array(3) {
["Month"]=>
string(1) "1"
["Country"]=>
string(2) "AU"
["Total_Sales"]=>
string(7) "9095.70"
}
[1]=>
array(3) {
["Month"]=>
string(1) "1"
["Country"]=>
string(2) "CA"
["Total_Sales"]=>
string(9) "113993.00"
}
[2]=>
array(3) {
["Month"]=>
string(1) "2"
["Country"]=>
string(2) "AU"
["Total_Sales"]=>
string(7) "7393.65"
}
[4]=>
array(3) {
["Month"]=>
string(1) "2"
["Country"]=>
string(2) "CA"
["Total_Sales"]=>
string(9) "100279.43"
}
Here is what I need:
array(2) {
[1]=>
array(2) {
["MONTH"]=>
string(1) "1"
["Total_Sales"]=>
float(123088.7)
}
[2]=>
array(2) {
["MONTH"]=>
string(1) "2"
["Total_Sales"]=>
float(107673.08)
}
I know I need to do a loop but not sure where to go from here.
$newarr=array();
foreach($results as $key) {
}
Edit: This loop gets me the results I need but throws Notices that I don't want.
$newarr=array();
foreach($results as $value) {
$Month = $value['MONTH'];
$Total_Sales = $value['Total_Sales'];
array_key_exists( $Month, $newarr ) ? $newarr[$Month]['MONTH'] = $Month : $newarr[$Month]['MONTH'] = 0;
array_key_exists( $Month, $newarr ) ? $newarr[$Month]['Total_Sales']+=$Total_Sales : $newarr[$Month]['Total_Sales'] = 0;
}
Notices in the results
Notice: Undefined index: Total_Sales in /var/www/html/analytics/views/sales_year_line_data.php on line 134
Notice: Undefined index: Total_Sales in /var/www/html/analytics/views/sales_year_line_data.php on line 134