Zugzwangle Posted February 7, 2013 Share Posted February 7, 2013 Hi all, I have this array: Array ( [3] => Array ( [Team1] => Array ( [brd_points] => 5 [ttl_points] => 1 ) [Team2] => Array ( [brd_points] => 5 [ttl_points] => 1 ) [Team3] => Array ( [brd_points] => 5 [ttl_points] => 1 ) [Team4] => Array ( [brd_points] => 5 [ttl_points] => 1 ) ) [2] => Array ( [Team2] => Array ( [brd_points] => 5 [ttl_points] => 2 ) [Team5] => Array ( [brd_points] => 1 [ttl_points] => 0 ) [Team3] => Array ( [brd_points] => 7 [ttl_points] => 2 ) [Team1] => Array ( [brd_points] => 5 [ttl_points] => 0 ) ) [1] => Array ( [Team2] => Array ( [brd_points] => 4 [ttl_points] => 2 ) [Team1] => Array ( [brd_points] => 6 [ttl_points] => 0 ) [Team5] => Array ( [brd_points] => 6 [ttl_points] => 0 ) [Team4] => Array ( [brd_points] => 2 [ttl_points] => 2 ) ) ) 1 I would like to get an array of the sum of all the [brd_points] and [ttl_points] for each team.. so... it would become.. Array ( [Team1] => Array ( [brd_points] => 16 // 5 + 5 + 16 [ttl_points] => 1 // 1 + 0 + 0 ) [Team2] => Array ( [brd_points] => ?? [ttl_points] => ?? ) etc... Quote Link to comment https://forums.phpfreaks.com/topic/274156-merging-array-keys/ Share on other sites More sharing options...
.josh Posted February 7, 2013 Share Posted February 7, 2013 foreach ($array as $i) { foreach ($i as $team => $tv) { $newArray[$team]['brd_points'] += $tv['brd_points']; $newArray[$team]['ttl_points'] += $tv['ttl_points']; } } print_r($newArray); FYI for future reference, it would make it easier on people trying to help if you post a serialize or var_export of the array instead of print_r. It makes it easy for people to rebuild your array. Quote Link to comment https://forums.phpfreaks.com/topic/274156-merging-array-keys/#findComment-1410759 Share on other sites More sharing options...
Barand Posted February 7, 2013 Share Posted February 7, 2013 if you want to avoid a shedload of "undefined" notices, then $totals = array(); foreach ($data as $subarray) { foreach ($subarray as $team => $scores) { if (!isset($totals[$team])) $totals[$team] = array(); foreach ($scores as $desc => $pts) { if (!isset($totals[$team][$desc])) $totals[$team][$desc] = 0; $totals[$team][$desc] += $pts; } } } echo '<pre>',print_r($totals, true),'</pre>'; Quote Link to comment https://forums.phpfreaks.com/topic/274156-merging-array-keys/#findComment-1410765 Share on other sites More sharing options...
Zugzwangle Posted February 7, 2013 Author Share Posted February 7, 2013 Thanks for your posts.. That really helped me, ta. Jeff Morris Quote Link to comment https://forums.phpfreaks.com/topic/274156-merging-array-keys/#findComment-1410791 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.