3v4l.org

run code in 200+ php & hhvm versions
Bugs & Features
<?php $csv = [ ['user' => 'user1', 'acct_num' => '1', 'value' => 32], ['user' => 'user1', 'acct_num' => '1', 'value' => 2], ['user' => 'user1', 'acct_num' => '2', 'value' => 32], ['user' => 'user1', 'acct_num' => '2', 'value' => 32], ['user' => 'user2', 'acct_num' => '1', 'value' => 312], ['user' => 'user2', 'acct_num' => '1', 'value' => 320], ]; $subtotals = []; $totals = []; $results = []; foreach($csv as $row) { list($user, $acct_num, $value) = array_values($row); $subtotal = isset($subtotals[$user][$acct_num]) ? $subtotals[$user][$acct_num] : 0; $subtotals[$user][$acct_num] = $subtotal + $value; $total = isset($totals[$user]) ? $totals[$user] : 0; $totals[$user] = $total + $value; } foreach ($subtotals as $user => $acct_nums) { foreach ($acct_nums as $acct_num => $value) { $total = $totals[$user]; $avg = $value / $total; $results[] = compact('user', 'acct_num', 'value', 'total', 'avg'); } } print_r($results);
Output for 5.6.0 - 5.6.30, hhvm-3.15.4, 7.0.0 - 7.3.0alpha1
Array ( [0] => Array ( [user] => user1 [acct_num] => 1 [value] => 34 [total] => 98 [avg] => 0.3469387755102 ) [1] => Array ( [user] => user1 [acct_num] => 2 [value] => 64 [total] => 98 [avg] => 0.6530612244898 ) [2] => Array ( [user] => user2 [acct_num] => 1 [value] => 632 [total] => 632 [avg] => 1 ) )