'PhP how to calculate moments with variables rows
I have 45 - 50 array rowss that are deserialized json return values in standard PhP array string format, from cURL with data that looks like the following:
Array
(
[0] => 0.00634000
[1] => 20.54182841
)
Array
(
[0] => 0.00637479
[1] => 31.21047749
)
Array
(
[0] => 0.00637480
[1] => 2.23450852
)
....
var_dump of data var_dump
I need to perform the following math calculation against the return data (note the incremental 1,2,3..)
((1 * 0.00634000 * 20.54182841) + (2 * 0.00637479 * 31.21047749) + (3 * 0.00637480 * 2.23450852)) / ((0.00634000 * 20.54182841) + (0.00637479 * 31.21047749) + (0.00637480 * 2.23450852))
....
assuming the following 3 array elements
0.1302351921194 + 0.3979204795969542 + 0.042733634739888 / 0.1302351921194 + 0.1989602397984771 + 0.014244544913296
then
0.5708893064562422 / 0.3434399768311731
array moments = 1.662268067112285
array length = 3
What would be the proper way to set this up in PhP if you do not know what how many rows will be in the array?
Solution 1:[1]
Simply use foreach()
. Example:
$var1 = 0; $var2 = 0; $count = 0;
foreach($arr as $k=>$v){
if(is_numeric($v[0]) && is_numeric($v[1])){
$var2 += $v[0] * $v[1];
$var1 += $var2 * ($k + 1);
$count++;
}
}
$result = $var1 / $var2;
echo 'Result: ' . $result . '<br /> Count: ' . $count;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |