php - 数组中值的总和

时间:2015-10-01 16:50:20

标签: php arrays multidimensional-array

我需要帮助来对数组中的值求和。该数组称为$ results,我需要将每个月的Total_Sales值相加。编辑 - 我有下面的循环,我需要得到结果;但是我得到了通知。如何改进代码以便我不会收到这些通知?

这是数组:

$结果

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

这就是我需要的:

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

我知道我需要做一个循环,但不知道从哪里开始。

$newarr=array();
foreach($results as $key) {

}

编辑:这个循环得到了我需要的结果,但却抛出了我不想要的通知。

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

结果中的注意事项

注意:未定义的索引:第134行/var/www/html/analytics/views/sales_year_line_data.php中的Total_Sales

注意:未定义的索引:第134行/var/www/html/analytics/views/sales_year_line_data.php中的Total_Sales

2 个答案:

答案 0 :(得分:0)

在你的循环中你只需添加值:

$newarr=array();
foreach($results as $val) {
  // index your new array by month so you can easily add to total sales
  $month = $val['Month'];
  $newarr[$month]['Month'] = $month;
  $newarr[$month]['Total_Sales'] += $val['Total_Sales'];
}

// to get rid of your month-based index, use array_values
$finalarray = array_values($newarr);

答案 1 :(得分:0)

我收集你需要的数组的键是月份整数(因为我可以看到它从1开始)。

我们试试看:

$totals = array();

foreach ($results as $result) {
    $currentMonth = $result['Month'];
    // For the first record for a given month, we need to add an "empty" record
    if (!array_key_exists($currentMonth, $totals)) {
        $totals[$currentMonth] = array(
            'MONTH' => $currentMonth,
            'Total_Sales' => 0,
        );
    }

    // Then we can sum totals
   $totals[$currentMonth]['Total_Sales'] += $result['Total_Sales'];
}

var_dump($results)给了我:

array (size=2)
  1 => 
    array (size=2)
      'MONTH' => string '1' (length=1)
      'Total_Sales' => float 123088.7
  2 => 
    array (size=2)
      'MONTH' => string '2' (length=1)
      'Total_Sales' => float 107673.08