PHP按月求和数组

PHP按月求和数组,php,arrays,Php,Arrays,请帮助我计算以下数组的和: Array ( [0] => Array ( [month] => Jan [planned] => 0.00 [actual] => 15102.70 ) [1] => Array ( [month] => Jan [planned] => 0.00 [actual] => 19452.40 ) [2] => Array ( [month] => Feb [planned] => 15629.80 [

请帮助我计算以下数组的和:

Array ( [0] => Array ( [month] => Jan [planned] => 0.00 [actual] => 15102.70 ) [1] => Array ( [month] => Jan [planned] => 0.00 [actual] => 19452.40 ) [2] => Array ( [month] => Feb [planned] => 15629.80 [actual] => 12478.38 ) [3] => Array ( [month] => Feb [planned] => 39150.00 [actual] => 28003.30 ) [4] => Array ( [month] => Feb [planned] => 8940.00 [actual] => 0.00 ) [5] => Array ( [month] => Mar [planned] => 3600.00 [actual] => 0.00 ) [6] => Array ( [month] => Mar [planned] => 15924.48 [actual] => 3196.05 ) [7] => Array ( [month] => Mar [planned] => 22612.50 [actual] => 14322.13 ) [8] => Array ( [month] => Mar [planned] => 26146.00 [actual] => 0.00 ) ) 
我想要每月的总和:

全部计划在一月份完成

所有实际费用均在1月份支付


每个月都一样。

您可以使用next
foreach循环

$res_pl = [];
$res_act = [];

foreach($data as $record){

    if (!isset($res_pl[$record['month']])) $res_pl[$record['month']] = 0;
    if (!isset($res_act[$record['month']])) $res_act[$record['month']] = 0;

    $res_pl[$record['month']] += $record['planned'];
    $res_act[$record['month']] += $record['actual'];
}

print_r($res_pl);  // all planned collected by month
print_r($res_act); // all actual collected by month
如果您需要一个函数,该函数将返回一个已定义月份的值,那么您可以使用下一个代码:

function getPlannedAndActual($data,$month){

    $res_pl = 0;    // default value
    $res_act = 0;   // default value

    foreach($data as $record){
        if (trim($record['month']) === $month){

            $res_pl += $record['planned'];   // sum of planned
            $res_act += $record['actual'];   // sum of actual
        }
    }

    // resultant array structure
    $res = [ $month => [
                       'planned' => $res_pl, 
                       'actual' => $res_act
                       ]
           ];
    return $res;
}

print_r(getPlannedAndActual($array,'Jan'));

到底是什么问题?请看。