在PHP动态变量中迭代

时间:2014-05-20 04:19:30

标签: php

function stepzero(){
    $alcount = $_POST["alcount"];//retrieve number of row
    $crcount = $_POST["crcount"];//retrieve number of coloumn

    for ($x=1; $x <=$crcount ; $x++) { //Loop for coloumn
        for ($y=1; $y <=$alcount ; $y++) { //Loop for row
            ${"v".$y."t".$x} = $_POST["r".$y."c".$x];//retrieve value of table
            ${"v".$y."t".$x} = ${"v".$y."t".$x}*${"v".$y."t".$x};//square the value
            ${"nv".$y."t".$x} = ${"nv".$y."t".$x} + ${"v".$y."t".$x}; //not working
            echo ${"nv".$y."t".$x};
            echo "<br>";
        }
    }
}

我有这个函数从表中检索值,将其平方然后求和。但是${"nv".$y."t".$x}返回与${"v".$y."t".$x}相同的值(它没有对它进行求和)。我该如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

这段代码可能更简单。

例如,这两行:

${"v".$y."t".$x} = ${"v".$y."t".$x}*${"v".$y."t".$x};//square the value
${"nv".$y."t".$x} = ${"nv".$y."t".$x} + ${"v".$y."t".$x}; //not working

可写得更好:

${"v".$y."t".$x} *= ${"v".$y."t".$x};//square the value
${"nv".$y."t".$x} += ${"v".$y."t".$x}; //not working

答案 1 :(得分:0)

如果你只想得到一堆数值的平方和,试试这个:

function stepzero(){
    $alcount = $_POST["alcount"];//retrieve number of row
    $crcount = $_POST["crcount"];//retrieve number of coloumn
    $sum = 0;

    for ($x=1; $x <=$crcount ; $x++) { //Loop for coloumn
        for ($y=1; $y <=$alcount ; $y++) { //Loop for row
            $sum += $_POST["r".$y."c".$x] * $_POST["r".$y."c".$x];
        }
    }

    return $sum;
}