I have a multi-dimensional array like this:
array(
0 => array(
11 => 18.000,
14 => 25.100,
15 => 5.000,
16 => 8.000,
19 => 21.600'
),
1 => array(
11 => 9.100,
12 => 2.700,
14 => 2.300,
15 => 18.800,
16 => 9.500,
17 => 6.900,
19 => 9.400'
),
2 => array(
14 => 5.700
),
3 => array(
17 => 2.800,
20 => 6.000
),
4 => array(
24 => 5.000,
25 => 6.000,
26 => 2.7
),
5 => array(
16 => 2.200
),
6 => array(
14 => 13.000,
15 => 2.000,
16 => 4.300,
19 => 6.000
),
7 => array(
32 => 5.000,
36 => 18.500
)
)
The second-level arrays have varying length. But I want to get the values of the elements with similar keys and add them together to get a grand total.
For example, if the array is called $multi_dime
. I would want to get $multi_dime[0][11]
add it to $multi_dime[1][11]
and so on.
If the key does not exist in a following array. It should just add 0
or ignore it. The code should proceed to do this for all keys in the second-level array and store the results in another array like:
array( 11 => 27.1, 14 => 46.1, ...)
How can I achieve this? The array will always be two dimensional, but can be of any length and the second level arrays can also be any length.
Just use a foreach or for loop. That is how you work with arrays, be it one, two, three, four, or two-hundred dimensional. Since you will have more than one sum, make the sums variable an array. Declare it outside your loop because you will need it when the loop is complete.
$sums = array();
foreach($multi_dime as $vals)
{
foreach($vals as $key=>$val)
{
// Now we are looping through all values in the second dimension.
// If the key is not in the sums array, make it.
if(!isset($sums[$key])) $sums[$key]=0;
// We add this sum to the key now.
$sums[$key]+= $val;
}
}
ksort($sums); // Just in case you want the keys in order.
print_r($sums); // See all the sums.