如何在php中递归添加数字

时间:2012-01-14 01:45:35

标签: php

我想添加$ colnum的最后一位数,如下所示。请参阅代码中的注释。

for($c=2;$c<$keynum;$c++){
...
...
$studentcomment = '';
for($col=1;$col<5;$col++){
    $colnum="col".$col."_".$c;// this will find col1_2, col2_2, col3_2, col4_2 
    $colnum= $this->input->post($colnum);// this will get value from post. 
    //e.g. col11, col12 col13 col14 or col15
    echo "colnum is ";
    echo $colnum; // this will be col12
    echo "<br />";
    $subgrade="";
    $subgrade = substr($colnum,-1);// get the last digit
    if($subgrade<5 AND !empty ($subgrade)){// 5 has no comment so excluded
        echo "subgrade is ";
        echo $subgrade;// this will be 2,3 or 4
        $total="";
        $total += $subgrade;// add all the subgrade to find the total
        echo "<br />";
        echo "Total collaboration marks is ";
        echo $total;
    }

    if(!empty($colnum)){
        $studentcomment .=$this->lang->line($colnum);//output all the comments 
from language file.
    }

}

但输出如下,而不是添加数字。

colnum is col15
colnum is col24
subgrade is 4
Total is 4
colnum is col33
subgrade is 3
Total is 3
colnum is col42
subgrade is 2
Total is 2

感谢您的帮助。谢谢。

2 个答案:

答案 0 :(得分:1)

您正在$total循环中重置for

$total=""; 

这需要移出循环。代码肯定会使用一些清理工具。

答案 1 :(得分:1)

我不确定我是否完全理解您的问题,但是如果您希望$total包含所有列的总数,那么您需要删除行$total = "";,或将其移到外面循环。这样就可以在for循环的每次迭代中重置总值。