我必须在PHP中实现一个算法而且我遇到了困难。
我有下表:http://cl.ly/image/1Z0K1g0z2c3y
对于每次迭代,(S)值计算如下:
S1 = V1 - P1
S2 =(V1-P1)+(V2-P2)
S3 =(V1-P1)+(V2-P2)+(V3-P3)
等等。
我的数组值如下所示:
Array
(
[0] => Array
(
[v] => 131.44
[p] =>
)
[1] => Array
(
[v] => 155.00
[p] =>
)
[2] => Array
(
[v] => 168.64
[p] =>
)
[3] => Array
(
[v] => 131.44
[p] => 131.44
)
[4] => Array
(
[v] => 280.00
[p] => 280.00
)
[5] => Array
(
[v] => 117.80
[p] => 117.80
)
[6] => Array
(
[v] => 70.68
[p] => 70.68
)
[7] => Array
(
[v] => 58.90
[p] => 58.90
)
是否可以使用for()循环计算每次迭代的总和?
答案 0 :(得分:1)
修改强>
假设你更新的数组叫做$ table:
// $S is array for S where sums are stored
$S = array();
$S[0] = $table[0][v] - $table[0][p]; // Perform the first row
for ($i=1; $i< count($table); $i++) { // Start at 2nd and continue on
$S[$i] = $S[($i-1)] + ($table[$i][v] - $table[$i][p]);
}
现在所有的$ S值都是这样填充的。如果要添加到表中:
$table[0][s] = $table[0][v] - $table[0][p]; // Perform the first row
for ($i=1; $i< count($table); $i++) { // Start at 2nd and continue on
$table[$i][s] = $table[$i-1][s] + ($table[$i][v] - $table[$i][p]);
}
是的,你可以,考虑到你想要S值为1,2,3 ......然后是。我假设V是一个数组,P是一个数组,所以你必须相应地改变,因为每个S可以基于前一个,我保留一个running_sum值,这样我们就不必迭代以前的V值和P,我们只使用S的最后一个值:
// $V is array for V and $P is array for P and
// $S is array for S where sums are stored
if (count($V) == count($P)) { // Check both V and P are same length
$running_sum = 0;
for ($i=0; $i< count($V); $i++) {
$running_sum += ($V[$i] - $P[$i]);
$S[$i] = $running_sum;
}
}
我们确实不需要运行sum变量,但我用它来使逻辑清晰,这里没有它:
// $V is array for V and $P is array for P and
// $S is array for S where sums are stored
if (count($V) == count($P)) { // Check both V and P are same length
$S[0] = $V[0] - $P[0]; // Perform the first row
for ($i=1; $i< count($V); $i++) { // Start at 2nd and continue on
$S[$i] = $S[($i-1)] + ($V[$i] - $P[$i]);
}
}