0

I have an array called $results that I need to sum the Total_Sales per Month. I have the code below that gives me the results I need but I also get notices. How do I improve the code?

$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's my code so far. The array that it returns are the results that I need but I get notices

Code

$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;
}

$newarr

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)
  }

Notices

Notice: Undefined index: Total_Sales in /var/www/html/analytics/views/sales_year_line_data.php on line 120

Notice: Undefined index: Total_Sales in /var/www/html/analytics/views/sales_year_line_data.php on line 120

Cory
  • 173
  • 3
  • 11
  • 2
    Use `isset();` to check if the value is there :) – Epodax Oct 01 '15 at 07:49
  • its actually in a loop so in some case your array may not have `Total_Sales` in it, as suggested above try `isset()` e.g `if(isset($newarr[$Month]['Total_Sales'])){......}` – noobie-php Oct 01 '15 at 07:54
  • Possible duplicate of [PHP: "Notice: Undefined variable" and "Notice: Undefined index"](http://stackoverflow.com/questions/4261133/php-notice-undefined-variable-and-notice-undefined-index) – Epodax Oct 01 '15 at 07:55

1 Answers1

0

This warning is arised since at very first time in loop , $newarr[$Month]['Total_Sales'] is not set so shothand sum is not allowed , so do it as below -

    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']=
           (isset($newarr[$Month]['Total_Sales'])?$newarr[$Month]['Total_Sales']:0)
           :$Total_Sales :
        $newarr[$Month]['Total_Sales'] = 0;
        }
Rohit Kumar
  • 1,948
  • 1
  • 11
  • 16