1

I am using php and have the following structure

<?php if(!empty($bids)): ?>
  <?php foreach ($bids as $bid):?>
     <tr>
         <td><?php if($bid['Bid']['debit'] > 0) : ?><?php echo $bid['Bid']['debit']; ?><?php else: ?>&nbsp;<?php endif; ?></td>
         <td><?php if($bid['Bid']['credit'] > 0) : ?><?php echo $bid['Bid']['credit']; ?><?php else: ?>&nbsp;<?php endif; ?></td>
     </tr>
  <?php endforeach; ?>
<?php endif;?>

Now i need to calculate the sum total in each case. I know its easy but not getting how to use loop within the foreach to calculate the total value. Please suggest how to do that loop.

If suppose for the first td sample output structrue is as like below, i need to add up all and just display 22 and not the array

0 2 0 20
0

3 Answers 3

4

Try with:

<?php

if(!empty($bids)) {
  $debitSum  = 0;
  $creditSum = 0;

  foreach ($bids as $bid) {
    $debit  = $bid['Bid']['debit'];
    $credit = $bid['Bid']['credit'];

    echo '<tr>';
    echo '<td>' . ( $debit > 0 ? $debit  : '&nbsp;' ) . '</td>';
    echo '<td>' . ( $credit> 0 ? $credit : '&nbsp;' ) . '</td>';
    echo '</tr>';

    $debitSum  += $debit;
    $creditSum += $credit;
  }

  echo '<tr style="font-weight: bold">';
  echo '<td>' . $debitSum . '</td>';
  echo '<td>' . $creditSum . '</td>';
  echo '</tr>';

}
?>

Edit:

If $bid['Bid']['debit'] (or credit too) is a string value, then cast it to int value:

$debit = (int) $bid['Bid']['debit'];
Sign up to request clarification or add additional context in comments.

Comments

1

Why don't you add a counter variable outside the foreach?

  <?php
  $total['debit'] = 0;
  $total['credit'] = 0;
  foreach ((array)$bids as $bid)
  {
     $debit = ($bid['Bid']['debit'] > 0)? $bid['Bid']['debit'] : 0;
     $credit = ($bid['Bid']['credit'] > 0)? $bid['Bid']['credit'] : 0;
     $total['debit'] += $debit;
     $total['credit'] += $credit;
     $output =<<<XHTML
     <tr>
         <td>{$debit}</td>
         <td>{$credit}</td>
     </tr>
  XHTML;
     echo $output;
  }
  ?>

Comments

0

It's better to define variable inside the loop and add values to the variable and then print the variable.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.