PHP:从一个变量动态添加每个输出的值


PHP: Add the value of each output dynamically from one variable

所以我正在使用ACF制作一个WP模板,其中有一个table。在此表中想要添加一些结果。现在,要获得总金额,我必须添加所有$price的值,每个值都会有所不同,因为它在repeater field中。

那么如何制作动态变量,然后将它们的值添加到新变量中呢?

我的代码:

<?php if (get_sub_field('offer_pr_ob')): while(has_sub_field('offer_pr_ob')): 
            $qt = floatval(get_sub_field('offer_pr_ob_qt'));
            $hrs = floatval(get_sub_field('offer_pr_ob_hrs'));
            $hrsRt = floatval(get_sub_field('offer_pr_ob_hrs-rt'));
            $hrsTot = $qt * $hrs;
            $price = $hrsTot * $hrsRt;
            $priceVat = $price * 1.25;  
            $priceTot = $price + $price; <-- this just outputs the value of 
the latest $price, e.g. "price*2" -->
?>
                                <tr class="pricingObject">
                                    <td><?php the_sub_field('offer_pr_ob_typ'); ?></td>
                                    <td><?php echo $qt; ?></td>
                                    <td><?php the_sub_field('offer_pr_ob_hrs-rt'); ?>.-</td>
                                    <td>
                                        <?php echo $hrs; ?>/<?php the_sub_field('offer_pr_ob_per'); ?></td>
                                    <td>
                                        <?php echo $hrsTot;?>h/&aring;r</td>
                                    <td><?php echo $price;.-</td>
                                    <td><?php echo $priceVat;?>.-</td>
                                </tr>
                                <?php endwhile; endif;?>
                                <tr class="pricingResult">
                                    <th>Total &aring;rskostnad</th>
                                    <th>&nbsp;</th>
                                    <th>&nbsp;</th>
                                    <th>&nbsp;</th>
                                    <th>&nbsp;</th>
                                    <th><?php echo $priceTot; ?>.-</th>
                                    <th>10 790 000.-</th>
                                </tr>
                            </table>
                    </div>
                    <?php endwhile; endif; ?>
您需要在

while 循环之外设置变量:我也更改了它以向您递增的变量添加价格。变量仅在您创建它们的循环中存在,while 循环之外的任何内容都无法使用它。

每次循环时,前一个$priceTot都被遗忘了,这就是为什么我们需要将其设置在循环之外,以便它保留所有以前的值,不要将while循环视为单个代码位,将其视为N x块...每次它运行它本质上是一个新的代码块,每次完成时,代码都结束了,信息从内存中清除了。

<?php 
$priceTot = 0;
if (get_sub_field('offer_pr_ob')): while(has_sub_field('offer_pr_ob')): 
        $qt = floatval(get_sub_field('offer_pr_ob_qt'));
        $hrs = floatval(get_sub_field('offer_pr_ob_hrs'));
        $hrsRt = floatval(get_sub_field('offer_pr_ob_hrs-rt'));
        $hrsTot = $qt * $hrs;
        $price = $hrsTot * $hrsRt;
        $priceVat = $price * 1.25;  
        $priceTot = $priceTot + $price; <-- this just outputs the value of