Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have 2 arrays as follows :-

$m_aggregate = array(
             'weighted' => array (40000,
                   30000,
                   90000,
                   0),
      'unweighted' => array (3000,
                     2000,
                     6000,
                     0),
      'weighted_sum' => 160000,
      'unweighted_sum' => 11000
     );

$f_aggregate = array(
             'weighted' => array (7000,
                           5000,
                           9000,
                           0),
      'unweighted' => array (500,
                            300,
                            600,
                            0),
      'weighted_sum' => 21000,
      'unweighted_sum' => 1400
     );

and wish to sum the individual elements so I get

$tot_aggregate = array(
             'weighted' => array (47000,
                          35000,
                      99000,
                  0),
      'unweighted' => array (3500,
                            2300,
                6600,
                0),
      'weighted_sum' => 181000,
      'unweighted_sum' => 12400
     );

I've tried using

function sum($arr1, $arr2)
{
    return($arr1+$arr2);
}

$tot_aggregate = array_map("sum", $m_aggregate, $f_aggregate);

print_r($tot_aggregate);

but this gives me weighted_sum and unweighted_sum , but not the weighted and unweighted arrays within the array summed.

Can anyone help? tia Jas

share|improve this question
add comment (requires an account with 50 reputation)

1 Answer

up vote 0 down vote accepted
function sum($arr1, $arr2)
{
    return is_array( $arr1) && is_array( $arr2)  
           ? array_map("sum", $arr1, $arr2) 
           : ($arr1 + $arr2); 

}

$tot_aggregate = sum($m_aggregate, $f_aggregate);

print_r($tot_aggregate);

Output :

Array
(
    [0] => Array
        (
            [0] => 47000
            [1] => 35000
            [2] => 99000
            [3] => 0
        )

    [1] => Array
        (
            [0] => 3500
            [1] => 2300
            [2] => 6600
            [3] => 0
        )

    [2] => 181000
    [3] => 12400
)
share|improve this answer
Som - many thanks. that worked :-) – jas105 Aug 1 at 14:25
1  
@jas105 - If it worked for you, please accept his answer. – Pé de Leão Aug 1 at 21:30
Som - is there a way to get the array key names 'weighted', 'unweighted' , 'weighted_sum', 'unweighted_sum' in the required output using your function? – jas105 Aug 6 at 16:16
add comment (requires an account with 50 reputation)

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.