【问题标题】:How to add PHP foreach looping calculated value in Javascript for every iteration如何为每次迭代在Javascript中添加PHP foreach循环计算值
【发布时间】:2019-03-21 12:24:17
【问题描述】:

我在 PHP 中有一个查询结果,并使用 foreach 循环通过在 html 表中生成新的 tr 来显示结果,但同时将在我想通过添加一些行使用 Javascript 显示的循环内计算一些值

我该怎么做?

PHP:

  <tbody>
    <?php
    $gTotalBorn = 0;
    $gTotalSanc = 0;
    $bTotalBorn = 0;
    $bTotalSanc = 0;
    foreach ($reNominalRoll as $key => $value) {
        if ($row_area->ADMIN_ID == $value->AREA_ID) {
            $gTotalBorn += $value->Borne;
            $gTotalSanc += $value->sanction;
            ?>
            <tr class="allrow">
                <td><?php echo $value->Rank ?></td>
                <td><?php echo $value->Part ?></td>
                <td><?php echo $value->sanction;
                    $bTotalSanc += $value->sanction; ?></td>
                <td><?php echo $value->Borne;
                    $bTotalBorn += $value->Borne; ?></td>
                <td><?php echo $value->TotalIn ?></td>
                <td><?php echo $value->TotalOut ?></td>
            </tr>
            <?php
        }
    }
    }
    ?>
    <!--Grand Total Row-->
    <tr>
        <td style="text-align: center; font-weight: bold;" colspan="5">Grand Total</td>
        <td style="text-align: center; font-weight: bold;"><?php echo $gTotalSanc; ?></td>
        <td style="text-align: center; font-weight: bold;"><?php echo $gTotalBorn; ?></td>
        <td></td>
        <td></td>
    </tr>
    </tbody>

Javascript:

if (allrow.hasClass('expectedRow')) {
                    $('.expectedRow').each(function () {
                        let thisRow = $(this);
                        let prevShip = thisRow.prevAll('.ships:first');
                        let prevUnit = thisRow.prevAll('.units:first');
                        let prevBranch = thisRow.prevAll('.units:first');

                        //thisRow.after('<tr><td colspan="6"><strong>Branch Total</strong></td></tr>');
                        thisRow.after('<tr>'+
                                        '<td><strong>Branch Total</strong></td>'+
                                        '<td></td>'+
                                        '<td><strong>'+"<?php echo $bTotalSanc; $bTotalSanc = 0;?>"+'</strong></td>'+
                                        '<td><strong>'+"<?php echo $bTotalBorn; $bTotalBorn = 0;?>"+'</strong></td>'+
                                        '<td></td>'+
                                        '<td></td>'+
                                    '</tr>');

                        // below conditions for identify the unit based on rowspan length
                        if (prevUnit.find('td[rowspan]').length == 2) {
                            // ship rowspan incremented by 1
                            let prevShipRowspan = parseInt(prevShip.find('td:first').attr('rowspan'));
                            let newPrevShipRowspan = prevShipRowspan+1;
                            prevShip.find('td:first').attr('rowspan',newPrevShipRowspan);

                            // unit rowspan incremented by 1
                            let unitRowspan = parseInt(prevUnit.find('td:first').attr('rowspan'));
                            let newUnitRowspan = unitRowspan+1;
                            prevUnit.find('td:first').attr('rowspan',newUnitRowspan);

                            // branch rowspan incremented by 1
                            let branchRowspan = parseInt(prevUnit.find('td:eq(1)').attr('rowspan'));
                            let newBranchRowspan = branchRowspan+1;
                            prevBranch.find('td:eq(1)').attr('rowspan',newBranchRowspan);
                        }

                        else if (prevUnit.find('td[rowspan]').length == 3) {
                            // ship rowspan incremented by 1
                            let prevShipRowspan = parseInt(prevShip.find('td:first').attr('rowspan'));
                            let newPrevShipRowspan = prevShipRowspan+1;
                            prevShip.find('td:first').attr('rowspan',newPrevShipRowspan);

                            // unit rowspan incremented by 1
                            let unitRowspan = parseInt(prevUnit.find('td:eq(1)').attr('rowspan'));
                            let newUnitRowspan = unitRowspan+1;
                            prevUnit.find('td:eq(1)').attr('rowspan',newUnitRowspan);

                            // branch rowspan incremented by 1
                            let branchRowspan = parseInt(prevBranch.find('td:eq(2)').attr('rowspan'));
                            let newBranchRowspan = branchRowspan+1;
                            prevBranch.find('td:eq(2)').attr('rowspan',newBranchRowspan);
                        }
                    });
                }

在上面的代码中,如何在javascript中添加$bTotalBorn$bTotalSanc的值而不是总数,随着循环值的同步将在javascript中更新

现在像这样显示总计,但需要显示小计

谁能帮帮我?

【问题讨论】:

  • 你想总结 $bTotalBorn $bTotalSanc 吗?
  • @MohammedYassineCHABLI 我已经更新了问题
  • 从上表中得到的期望值是多少?
  • 也许将每个小计存储在 PHP 中的数组中,并在 JS 中访问当前迭代函数中想要的小计(.each() 的第一个参数)。
  • 你为什么不在 PHP 中构建小计行呢?

标签: javascript php foreach


【解决方案1】:

下面是我猜你正在尝试做的一个例子。

为了让代码 sn-p 工作,我做了一个非 PHP 示例。

  • 表格行在 HTML 中间生成,尽可能与您在 PHP 中所做的相对应。
  • 小计单元格是用 Javascript 生成的,就像您的帖子中一样。

我的 sn-p 只是在这里为您提供问题的初步解决方案。我是根据您的意愿做的(我主要想到“同步循环值将在 javascript 中更新”,所以如果我是对的,请在 JS 中使用 PHP 变量)。

$(document).ready(() => {
  $('table > tbody > tr').each((i, tr) => {
    const subtotalCellHtml = `<td>${subtotalsA[i]}</td><td>${subtotalsB[i]}</td>`;
    
    $(tr).append(subtotalCellHtml);
  });
});
table {
  border-collapse: collapse;
}

table td,
table th {
  border: 1px solid #000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<table>
  <thead>
    <tr>
      <th>Values A</th>
      <th>Values B</th>
      <th>Total A</th>
      <th>Total B</th>
    </tr>
  </thead>

  <tbody>
    <!-- generated <tr> -->
    <!-- below a <script> for imitating your PHP -->
    <script>
      /*
        The code below is in Javascript but should look like your PHP.
        I placed this code part here because your PHP is in the middle your HTML,
        I tried to have something similar of your post.
      */
    
      /** @var {array.<array>} Test values. */
      const valuesA = [[
        4, 5, 9, 1
      ], [
        2, 1, 8, 11
      ]];
      
      const valuesB = [[
        1, 2, 1, 1
      ], [
        3, 1, 1, 1, 2
      ]];
      
      /** @var {array.<number>} List of subtotalsA. */
      let subtotalsA = [],
      /** @var {array.<number>} List of subtotalsB. */
        subtotalsB = [],
      /** @var {number} Total of all valuesA. */
        totalA = 0,
      /** @var {number} Total of all valuesB. */
        totalB = 0;

      $(document).ready(() => {
        for (let i in valuesA) {
          // Line below is the same as looping through valuesA[i] and incrementing a var.
          const sumA = valuesA[i].reduce((acc, e) => (acc + e));
          // Same for valuesB[i]
          const sumB = valuesB[i].reduce((acc, e) => (acc + e));

          subtotalsA.push(sumA);
          totalA += sumA;
          subtotalsB.push(sumB);
          totalB += sumB;

          // Building table rows without subtotal like in your PHP.
          const rowHtml = `<tr>
            <td>${valuesA[i].join(', ')}</td>
            <td>${valuesB[i].join(', ')}</td>
          </tr>`;

          $('table > tbody').append(rowHtml);
        }
      });
    </script>
  </tbody>
  
  <tfoot>
    <tr>
      <th colspan="2">Grand Total</th>
      <!-- generated <th> -->
      <script>
        $(document).ready(() => {
          const totalCellHtml = `<th>${totalA}</th><th>${totalB}</th>`;
          
          $('table > tfoot > tr').append(totalCellHtml);
        });
      </script>
    </tr>
  </tfoot>
</table>

如果我的回答没有纠正您的问题(或没有帮助您),请告诉我,我可能误解了您的问题。

【讨论】:

    猜你喜欢
    • 2011-09-07
    • 2018-09-01
    • 1970-01-01
    • 2016-04-09
    • 2017-01-15
    • 1970-01-01
    • 1970-01-01
    • 2021-03-28
    • 2017-09-05
    相关资源
    最近更新 更多