How do I sum up weighted arrays in PHP?
        Posted  
        
            by christian studer
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by christian studer
        
        
        
        Published on 2008-10-24T09:40:53Z
        Indexed on 
            2010/05/29
            7:32 UTC
        
        
        Read the original article
        Hit count: 380
        
Hod do I multiply the values of a multi-dimensional array with weigths and sum up the results into a new array in PHP or in general?
The boring way looks like this:
$weights = array(0.25, 0.4, 0.2, 0.15);
$values  = array
           ( 
             array(5,10,15), 
             array(20,25,30), 
             array(35,40,45), 
             array(50,55,60)
           );
$result  = array();
for($i = 0; $i < count($values[0]); ++$i) {
  $result[$i] = 0;
  foreach($weights as $index => $thisWeight)
    $result[$i] += $thisWeight * $values[$index][$i];
}
Is there a more elegant solution?
© Stack Overflow or respective owner