How do I multiply the values of a multi-dimensional array with weights 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?
Depends on what you mean by elegant, of course.
EDIT: Sorry for not reading your example better. I make result a copy of values, since array_walk works by reference.