How do I sum up weighted arrays in PHP?
- by christian studer
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?