【问题标题】:Increment Total in Loop PHP循环 PHP 中的增量总计
【发布时间】:2019-02-12 07:26:23
【问题描述】:

我有这样的循环:

值 A 值 B 值 C 总计 X - X 总计 X X - X 总计 X X - X 总计 X X - X 总计 X X - X 总计 X

我想要总和 X,这是我的代码:

<table border="1">
<tr>
    <th>Value A</th>
    <th>Value B</th>
    <th>Value C</th>
    <th>Total</th>
</tr>
<?php
for($i = 1; $i <= 5; $i++) {
?>
<tr>
    <?php
    for($ii = 1; $ii <= 3; $ii++) {
        $a = ($ii % 2 == 0) ? "-" : "X";
        echo "<td>".$a."</td>";
    }
    ?>
    <td>Total X</td>
</tr>
<?php
}
?>
</table>

有什么技巧可以用 PHP 求和吗?

非常感谢!

【问题讨论】:

  • 如果'x'是数字那么你可以像$total = $a + $b + $c;一样添加它们如果$a、$b、$c是字符串数字那么你可以转换它们(int)$a + (int)$b + (int)$c;但不要忘记检查它是数字还是只是-
  • 这些值是从哪里来的,是从数组中来的吗?目前这不显示除行号以外的任何值,所以我们应该如何知道要添加什么。
  • 对不起,我已经更新了我的问题

标签: php loops sum


【解决方案1】:

从新代码更新:

<table border="1">
<tr>
    <th>Value A</th>
    <th>Value B</th>
    <th>Value C</th>
    <th>Total</th>
</tr>
<?php for($i = 1; $i <= 5; $i++) { ?>
    <?php $total = 0; ?>
    <tr> 
        <?php 
            for($ii = 1; $ii <= 3; $ii++) { 
                $a = ($ii % 2 == 0) ? "-" : "X";
                if($a == "X") $total++;
                echo "<td>".$a."</td>";
            } 
        ?>
        <td><?php echo $total ?></td>
    </tr>
<?php } ?>

【讨论】:

  • 我认为@Kemal 不想计算。他只想要它们的总和。
  • 我认为这正是他想要的。总共 X :)
  • 对不起,我的代码是这样的:".$a.""; } ?>
    Value A Value B Value C 总计
    总 X
  • 我已经更新了。如果它是你想要的,请告诉我。如果是,请将我的答案标记为正确的。
  • 没问题。请将我的答案标记为正确答案。谢谢!
【解决方案2】:

您只需将其转换为int,然后将它们相加即可:

<table border="1">
    <tr>
        <th>Value A</th>
        <th>Value B</th>
        <th>Value C</th>
        <th>Total</th>
    </tr>
    <?php
    for($i = 1; $i <= 10; $i++) {
        $a = ($i % 2 == 0) ? "10" : "-";
        $b = ($i % 2 == 0) ? "-" : "20";
        $c = ($i % 2 == 0) ? "15" : "-";
        $total = (int)$a + (int)$b + (int)$c;
        $res = "<tr>";
        $res .= "  <td>".$a."</td>";
        $res .= "  <td>".$b."</td>";
        $res .= "  <td>".$c."</td>";
        $res .= "  <td>Total ".$total."</td>";
        $res .= "</tr>";
        echo $res;
    }
    ?>
</table>

【讨论】:

    【解决方案3】:

    对不起,我的代码是这样的:

    <table border="1">
    <tr>
        <th>Value A</th>
        <th>Value B</th>
        <th>Value C</th>
        <th>Total</th>
    </tr>
    <?php
    for($i = 1; $i <= 5; $i++) {
    ?>
    <tr>
        <?php
        for($ii = 1; $ii <= 3; $ii++) {
            $a = ($ii % 2 == 0) ? "-" : "X";
            echo "<td>".$a."</td>";
        }
        ?>
        <td>Total X</td>
    </tr>
    <?php
    }
    ?>
    </table>
    

    我想计算 X 的总数 使用 PHP 的任何技巧

    【讨论】:

    • 请更新您的问题,而不是发布更新作为答案。为此,请使用问题下方的edit 按钮。当你在做的时候,请详细说明 totaling 应该如何工作。脚本应该如何总结“X”和“-”。
    • 谢谢!请同时添加对“Total X”的说明。
    • 总 X 来自值 A n 值 B n 值 C 是动态循环
    • 对你的问题 :) 不在这里。
    猜你喜欢
    • 2021-01-13
    • 2011-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多