数组中值的总和



我需要帮助来求和数组中的值。数组名为$results,我需要对每个月的Total_Sales值求和。编辑-我有下面的循环,我需要得到的结果;然而我收到通知。我怎样才能改进代码,使我不会收到这些通知?

这是数组:

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

这是我需要的:

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

结果

注意事项

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

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

在循环中添加值:

$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开始)。

让我们试试:

$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

相关内容

  • 没有找到相关文章

最新更新