How to use loop within foreach in php to add numbers - php

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: ?> <?php endif; ?></td>
<td><?php if($bid['Bid']['credit'] > 0) : ?><?php echo $bid['Bid']['credit']; ?><?php else: ?> <?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

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 : ' ' ) . '</td>';
echo '<td>' . ( $credit> 0 ? $credit : ' ' ) . '</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'];

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

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

Related

How to sum total value of any foreach loop result

I want to show Total Salary, which is the sum of all employee's net salary. How can I do that? I have tried some code but its not working
<tbody>
<?php
$salary = 0;
if (!empty($emp_salary_info)):foreach ($emp_salary_info as $v_emp_salary):
$salary = $salary + $v_emp_salary->basic_salary;
?>
<tr>
<td><?php echo $v_emp_salary->employment_id; ?></td>
<td><?php echo $v_emp_salary->first_name . ' ' . $v_emp_salary->last_name ?></td>
<td><?php echo $gross = $v_emp_salary->basic_salary + $v_emp_salary->house_rent_allowance + $v_emp_salary->medical_allowance + $v_emp_salary->special_allowance + $v_emp_salary->fuel_allowance + $v_emp_salary->phone_bill_allowance + $v_emp_salary->other_allowance ?></td>
<td><?php echo $deduction = $v_emp_salary->tax_deduction + $v_emp_salary->provident_fund + $v_emp_salary->other_deduction ?></td>
<?php $net_salary = $gross - $deduction ?>
<td><?php echo $net_salary ?></td>
<td><?php
if ($v_emp_salary->employment_type == 1) {
echo 'Provision';
} else {
echo 'Permanent';
}
?></td>
<td><?php echo btn_view('admin/payroll/view_salary_details/' . $v_emp_salary->employee_id); ?></td>
<td>
<?php echo btn_edit('admin/payroll/manage_salary_details/' . $v_emp_salary->employee_id . '/' . $v_emp_salary->designations_id); ?>
</td>
</tr>
<?php endforeach; ?>
<?php endif; ?>
</tbody>
this is code I have tried for sum the net salary
<?php
$salary = 0;
if (!empty($emp_salary_info)):foreach ($emp_salary_info as $v_emp_salary):
$salary = $salary + $v_emp_salary->basic_salary;
echo 'Total Salary :'
?>
<?php echo $salary; ?>
I think you are using data-tables for displaying table records. Try to print Total after completing record calculations.
In image you are displaying total before completing process.
Also change few lines of code
if(!isset($v_emp_salary->basic_salary) || empty($v_emp_salary->basic_salary) || !is_numeric($v_emp_salary->basic_salary))
{
$v_emp_salary->basic_salary = 0;
}
$salary = $salary + $v_emp_salary->basic_salary;
Still if you do not find total try to check data inside $emp_salary_info it may have empty or wrong data with salary.

showing 2nd page in a paginated table in a primary content div in php

Good Evening/morning,
I have a table which is paginated. The first page shows up in a primarycontent div, which is where i want it..however when clicking on page 2, 3..etch it opens up in a different link, I want it to open up in the primary content div like the first page, but can't figure out how to do it. Also when clicking the previous button it goes to page 1, instead of the page before the current page..ex on page 50, goes to page 1. Here is my code.
<?php
require_once ('mysqli_connect.php');
$display = 30;
if (isset($_GET['p']) && is_numeric ($_GET['p']))
{
$pages = $_GET['p'];
} else {
$q = "SELECT COUNT(NewCustomerID) FROM customer";
$r = #mysqli_query($dbc, $q);
$row = #mysqli_fetch_array ($r, MYSQLI_NUM);
$records = $row[0];
if ($records > $display){//more than 1 page.
$pages = ceil($records/$display);
} else {
$pages = 1;
}
} // end of p IF
if (isset($_GET['s']) && is_numeric ($_GET['s']))
{
$start = $_GET['s'];
} else {
$start = 0;
}
$q = "SELECT(NewCustomerID) AS customerid,
(OldCustomerID) AS oldcustomerid,
(FirstName) AS FirstName,
(MiddleName) AS MiddleName,
(LastName) AS LastName,
(UserName) AS UserName,
(CarID) AS CarID,
(CarColorID) AS CarColorID,
(ComputerID) AS ComputerID,
(IsLaptop) AS LaptopID,
(RaceID) AS RaceID,
(ResidenceID) AS ResidenceID,
(BirthMonthID) AS BirthMonthID
FROM customer ORDER BY LastName ASC LIMIT $start, $display";
$r = #mysqli_query($dbc, $q); if(!$r){die(mysqli_error($dbc));}
Echo '<table>
<tr>
<td><b>NewCustomerID </b></td>
<td><b>OldCustomerID </b></td>
<td><b>FirstName </b></td>
<td><b>MiddleName </b></td>
<td><b>LastName </b></td>
<td><b>UserName </b></td>
<td><b>CarID </b></td>
<td><b>CarColorID </b></td>
<td><b>ComputerID </b></td>
<td><b>IsLaptop </b></td>
<td><b>RaceID </b></td>
<td><b>ResidenceID </b></td>
<td><b>BirthMonthID </b></td>
</tr>';
$bg = '#eeeeee'; // set initial back ground color
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
$bg = ($bg =='#eeeeee' ? '#ffffff' : '#eeeeee'); // switch the background color.
echo '<tr bgcolor="' . $bg . '">
<td>' . $row['customerid'] . '</td>
<td>' . $row['oldcustomerid']. '</td>
<td>' . $row['FirstName']. '</td>
<td>' . $row['MiddleName']. '</td>
<td>' . $row['LastName']. '</td>
<td>' . $row['UserName'].'</td>
<td>' . $row['CarID'].'</td>
<td>' . $row['CarColorID'].'</td>
<td>' . $row['BirthMonthID'].'</td>
<td>' . $row['ComputerID'].'</td>
<td>' . $row['LaptopID'].'</td>
<td>' . $row['RaceID'].'</td>
<td>' . $row['ResidenceID'].'</td>
</tr>';
} // end of while loop
echo '</table>';
mysqli_free_result($r);
mysqli_close($dbc);
// make the links to the other pages if necessary
if ($pages >1) {
// add some spaces and start a paragraph
echo '<br /> <p>';
// determine what page the script is on:
$current_page = ($start/$display)+1;
// if it's not the first page, make a previous link;
if ($current_page !=1) {
echo 'Previous ';
}
for ($i = 1; $i <= $pages; $i++) {
if ($i != $current_page) {
echo '<a href="#" ' . (($display * ($i - 1))) . '&p=' . $pages . '">'
. $i . '</a> ';
}else{
echo $i . ' ';
}
}// end of FOR loop
// if it is not the last page, make a next button
if ($current_page != $pages) {
echo 'Next';
}
echo '</p>'; // close the paragraph
} // endo of links section
?>
Save yourself a ton of time and use a pre-engineered grid. My grid of choice is DataTables It's got all the bugs and browser inconsistencies taken care of already, and paging is as simple as one line of code. If you want to get really simple, you could output your entire table and let datatables sort out the paging, as well as sorting, filtering, etc. If you're like me and have to deal with a lot of results, you can also load data via ajax and have datatables actually assemble the dom. Either way, it's quicker than writing your own.
First of all, you should pass in GET/POST parameter which will carry the page to show. After you grab it from there, fro example in variable $page, you can use it SQL query with keyword OFFSET and LIMIT, like LIMIT 10 OFFSET 2, that gives you exactly rows from 11 to 20 items numbers.
Hope that's exactly what you need.
EDITED
<?php
$route = '/index.php?p='; // where to go on click page
$total = ($records % $display) != 0 ? floor($records / $display) + 1 : $records / $display; // total pages count
$current = isset($_GET['p']) ? $_GET['p'] : 1; // current page number
$last = 1; // init value of the last page
?>
<p class="pager">
<?php if ($total <= 9): ?>
<?php for ($i = 1; $i <= $total; $i++): ?>
<a href="<?php echo $route, $i; ?>" <?php if ($current == $i) echo 'class="acitve"'; ?>><?php echo $i; ?></a>
<?php endfor; ?>
<?php else: ?>
<?php
$rbound = $current + 1;
$lbound = $current - 1;
if ($lbound < 1)
$lbound = 1;
if ($rbound > $total)
$rbound = $total;
for ($i = 1; $i <= 3; $i++):
?>
<a href="<?php echo $route, $i; ?>" <?php if ($current == $i) echo 'class="acitve"'; ?>><?php echo $i; ?></a>
<?php $last = $i; ?>
<?php endfor; ?>
<?php if ($lbound <= $last): ?>
<?php for ($i; $i <= $rbound; $i++): ?>
<a href="<?php echo $route, $i; ?>" <?php if ($current == $i) echo 'class="acitve"'; ?>><?php echo $i; ?></a>
<?php $last = $i; ?>
<?php endfor; ?>
<?php else: ?>
<?php echo $lbound == $last + 1 ? '' : '...'; ?>
<?php endif; ?>
<?php if ($lbound > 3 && $rbound < $total - 2): ?>
<?php for ($i = $lbound; $i <= $rbound; $i++): ?>
<a href="<?php echo $route, $i; ?>" <?php if ($current == $i) echo 'class="acitve"'; ?>><?php echo $i; ?></a>
<?php $last = $i; ?>
<?php endfor; ?>
<?php endif; ?>
<?php if ($rbound >= $total - 2): ?>
<?php for ($i = $lbound; $i < $total - 2; $i++): ?>
<a href="<?php echo $route, $i; ?>" <?php if ($current == $i) echo 'class="acitve"'; ?>><?php echo $i; ?></a>
<?php $last = $i; ?>
<?php endfor; ?>
<?php $last = $last > $total - 4 ? $last : $total - 2; ?>
<?php else: ?>
<?php echo $rbound == $total - 3 ? '' : '...'; ?>
<?php $last = $total - 2; ?>
<?php endif; ?>
<?php for ($i = $total - 2; $i <= $total; $i++): ?>
<a href="<?php echo $route, $i; ?>" <?php if ($current == $i) echo 'class="acitve"'; ?>><?php echo $i; ?></a>
<?php endfor; ?>
<?php endif; ?>
</p>
That's all in above gives you pager rendered as: 1 2 3 ... 12 13 14 ... 18 19 20, here current page is 13, so it shows first 3 pages number, current page +/- 1 page and last 3 page numbers. So for the first page it would be: 1 2 3 ... 18 19 20, same for the last. Also adds CSS class active to the current page link.

ID in an html tag inside a php script

<?php
foreach ($myquery_domain->result() as $row ){
$domain = $row->domain;
$domain_id = $row->domain_id;
echo '<tr>';
echo '<td>';
echo '<span class="flip_domain" id="$domain_id">+</span>'.$domain;
echo '</td>';
echo '</tr>';
?>
Hi, I want my $domain_id to be the ID of my . Could Someone help me pls. Thank you.
<?php
foreach ($myquery_domain->result() as $row ){
$domain = $row->domain;
$domain_id = $row->domain_id;
echo '<tr>';
echo '<td>';
echo '<span class="flip_domain" id="'.$domain_id.'">+</span>'.$domain;
echo '</td>';
echo '</tr>';
?>
You'll have to concatenate it with a . - same as $domain:
echo '<span class="flip_domain" id="'.$domain_id.'">+</span>'.$domain;
Using single quotes for string literals means that PHP won't substitute variables for you. So, use double-quotes instead:
echo "<span class='flip_domain' id='$domain_id'>+</span>".$domain;
I like the readable syntax:
<?php
foreach ($myquery_domain->result() as $row ){
$domain = $row->domain;
$domain_id = $row->domain_id;
?>
<tr>
<td>
<span class="flip_domain" id="<?php echo $domain_id; ?>">+</span> <?php echo $domain; ?>
</td>
</tr>
<?php
}
?>

PHP: End and start a new <tr> after 6 rows

I want to make a table, and then for each 6 rows should have a tr, and then the rows are inside td.
So example:
<tr>
<td><?php echo $show[id]; ?></td> // 1
<td><?php echo $show[id]; ?></td> // 2
<td><?php echo $show[id]; ?></td> // 3
<td><?php echo $show[id]; ?></td> // 4
<td><?php echo $show[id]; ?></td> // 5
<td><?php echo $show[id]; ?></td> // 6
</tr> <tr> // start new tr after 6 rows
...repeat the tds
How can i do something like this?
I have tried myself doing
<tr>
<?php
while ($show == mysql_fetch_array($query)){ ?>
<td><?php echo $show[id]; ?></td>
<?php } ?>
</tr>
But as you can see this just inserts everything in one tr..
Thank you
<tr>
<?php
$c = 0; // Our counter
$n = 6; // Each Nth iteration would be a new table row
while ($show = mysql_fetch_array($query))
{
if($c % $n == 0 && $c != 0) // If $c is divisible by $n...
{
// New table row
echo '</tr><tr>';
}
$c++;
?>
<td><?php echo $show[id]; ?></td>
<?php
} ?>
</tr>
Related links:
Modulus operator (%) on php.net
Count the number of lines if the modulo 6 is null then echo the </tr><tr>
<tr>
<?php
$i=0;
while ($show == mysql_fetch_array($query)){ ?>
<td><?php echo $show[id]; ?></td>
<?php if(++$i%6 == 0) echo '</tr><tr>'; ?>
<?php } ?>
</tr>
You can do:
<tr>
<?php
$count = 0;
while ($show = mysql_fetch_array($query)){
if($count == 6) {
$count = 0;
echo "</tr> <tr>";
}
echo "<td>".$show[id]."</td>";
$count++;
}
</tr>
You’re accidentally using the comparison operator == instead of an assignment operator =.
And to always put six cells into each row, I’d do this:
$perRow = 6;
$counter = 0;
echo '<tr>';
while ($show = mysql_fetch_array($query)) {
if ($counter % $perRow === 0 && $counter !== 0) {
echo '</tr><tr>';
}
echo '<td>', $show['id'], '</td>';
$counter++;
}
while ($counter++ % $perRow !== 0) {
echo '<td></td>';
}
echo '</tr>';
This will ensure that each row is properly filled with six cells.
<?php
$countRows = 0;
while ($show == mysql_fetch_array($query)){
if($countRows == 0) echo '<tr>';
?>
<td><?php echo $show[id]; ?></td>
<?php
$countRows++;
if($countRows == 6){
$countRows = 0;
echo '</tr>';
}
?>
<?php } ?>
<?php if($countRows < 6) echo '</tr>'; ?>

Cross referenced tables from multi-dimensional arrays php?

How do it turn a multidimensional array like:
$fruits['apples']['blue'] = 24;
$fruits['bananas']['blue'] = 12;
$fruits['apple']['red'] = 34;
$fruits['gooseberries']['orange'] = 4;
$fruits['oranges']['red'] = 12;
into a cross referenced table like:
alt text http://1updesign.org/uploads/p24.png
$cols = array('blue', 'red', 'orange');
echo '<table>';
echo '<thead><tr><td></td><th scope="col">' . implode('</th><th scope="col">', $cols) . '</th></tr></thead>';
echo '<tbody>';
foreach($fruits as $label => $row)
{
echo '<tr>';
echo '<th scope="row">' . $label . '</th>';
foreach($cols as $k)
{
echo '<td>' . (isset($row[$k]) ? $row[$k] : 0) . '</td>';
}
echo '</tr>';
}
echo '</tbody>';
echo '</table>';
You’ll want some HTML escaping and such, but that’s the gist of it.
Your array is bad designed. How should one know, that apples is the same as apple. Your array should be constructed this way:
$fruits['apples']['blue'] = 24;
$fruits['apples']['read'] = 24;
$fruits['bananas']['blue'] = 12;
$fruits['gooseberries']['orange'] = 4;
$fruits['oranges']['red'] = 12;
Then iterating is easy. The first level of the array are the rows. So:
<?php
$column_head = array();
foreach($fruits as $key => $value) {
$column_head = array_merge($column_head, array_keys($value));
}
$column_head = array_unique($column_head);
print_r($column_head);
?>
<table>
<tr>
<th></th>
<?php foreach($column_head as $head): ?>
<th><?php echo $head; ?></th>
<?php endforeach; ?>
</tr>
<?php foreach($fruits as $fruit => $amount): ?>
<tr>
<td><?php echo $fruit ?></td>
<?php foreach($column_head as $head): ?>
<td><?php echo isset($amount[$head]) ? $amount[$head] : 0 ?></td>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
</table>
This generates which columns to use on fly, but it can be hardcoded which might be easier. As the code uses a lot loops it might be not that efficient...

Categories