w3outlook
w3outlook

Reputation: 853

How to add PHP foreach looping calculated value in Javascript for every iteration

I have a query result in PHP and using foreach loop showing the result by generating new tr in html table but at the same time some value will be calculated inside the loop that I want to show using Javascript by adding some rows

How can I do this?

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);
                        }
                    });
                }

In the above code, how to add $bTotalBorn and $bTotalSanc value add in javascript but not total, with the looping value synchronously will be update in javascript

Now showing the grand total like this but need to show subtotal screenshot

Can anyone help me?

Upvotes: 0

Views: 79

Answers (1)

K&#233;vin Bibollet
K&#233;vin Bibollet

Reputation: 3623

Below an example of what I guess you are trying to do.

I made a no-PHP example in order for the code snippet to work.

  • Table rows are generated in the middle of the HTML for corresponding as much as possible at what you did in PHP.
  • Subtotal cells are generated in Javascript, as in your post.

My snippet is just here to give you a start solution of your issue. I made it in function of how you would like to do (I mainly think of "with the looping value synchronously will be update in javascript", so usage PHP variables in JS if I am right).

$(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>

If my answer is not correcting your issue (or is not helping you), please tell me, I may have misunderstood what your issue was.

Upvotes: 1

Related Questions