Jump to content

Merging array keys.


Zugzwangle

Recommended Posts

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...

Link to comment
https://forums.phpfreaks.com/topic/274156-merging-array-keys/
Share on other sites

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.

Link to comment
https://forums.phpfreaks.com/topic/274156-merging-array-keys/#findComment-1410759
Share on other sites

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

Link to comment
https://forums.phpfreaks.com/topic/274156-merging-array-keys/#findComment-1410765
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.