How to calculate cumulative sum in PHP? - php

I want to calculate the sum and output a two columns table. But, the format is wrong. The numbers are all packed in one line.
<td>
<?php
for ($j = 1; $j <= 10; $j++)
{
print "<tr>";
print $j;
print "</tr>";
}
?>
</td>
<td>
<?php
$sum = 0;
for($i = 1; $i<=10; $i++)
{
print "<tr>";
print $sum = $sum + $i;
print "</tr>";
}
?>
</td>

Here, we would be writing one or two for loops, join our desired HTML string, and finally we would print it.
Test:
<?php
$html = '<tr>';
for ($j = 1; $j <= 10; $j++) {
$html .= "<td>" . $j . "</td>";
}
$html .= '</tr>';
$html .= '<tr>';
$sum = 0;
for ($i = 1; $i <= 10; $i++) {
$sum += $i;
$html .= "<td>" . $sum . "</td>";
}
$html .= '</tr>';
print($html);
?>
We would be also adding table open and close tags (<table>, </table>):
<?php
$html = '<table>';
$html .= '<tr>';
$html .= "<td>Number</td>";
for ($j = 1; $j <= 10; $j++) {
$html .= "<td>" . $j . "</td>";
}
$html .= '</tr>';
$html .= '<tr>';
$html .= "<td>Cumulative Sum</td>";
$sum = 0;
for ($i = 1; $i <= 10; $i++) {
$sum += $i;
$html .= "<td>" . $sum . "</td>";
}
$html .= '</tr>';
$html .= '</table>';
print($html);
?>
For two columns, we would just use one for` loop:
<?php
$html = '<table>';
$html .= "<tr><th>Number</th><th>Cumulative Sum</th></tr>";
for ($j = 1; $j <= 10; $j++) {
$html .= "<tr>";
$html .= "<th>" . $j . "</th>";
$sum += $j;
$html .= "<th>" . $sum . "</th>";
$html .= "</tr>";
}
$html .= '</table>';
print($html);

I ended up here when looking to get a cumulative sum in PHP. For the ones like me, I wrote the following function. It's safe for empty arrays as well.
function cumsum ($arr) {
return array_reduce($arr, function ($c, $i) { $c[] = end($c) + $i; return $c; }, []);
}

Related

Is there a way to make a NxM table where each cell has two subcells on the bottom?

How do I make a NxM table where each cell has two rows and its second row has two columns, but by using rowspan or colspan? I want to make something like this:
Here is my attempt.
Artikal.php:
public function get_html()
{
$html = "";
$html .= "<td>";
if (isset($this->sifra) && isset($this->naziv) && isset($this->cena) && isset($this->kolicina)) {
if ($this->kolicina > 0) {
$html .= "<img src=\"images/" . str_replace(" ", "-", $this->naziv) . jpg\" width=\"100\">";
$html .= "<br>";
$html .= "<span class=\"sifra\">{$this->sifra}</span>";
$html .= "<span class=\"cena\">{$this->cena} DIN</span>";
} else {
$html .= "<img src=\"images/none.png\" width=\"100\">";
$html .= "<br>";
$html .= "<span class=\"sifra\">{$this->sifra}</span>";
$html .= "<span class=\"cena\">{$this->cena} DIN</span>";
}
} else {
$html .= "<img src=\"images/none.jpg\" width=\"100\">";
$html .= "<br>";
$html .= "<span class=\"sifra\">X</span>";
$html .= "<span class=\"cena\">X</span>";
}
$html .= "</td>";
return $html;
}
index.php
if (isset($artikli)) {
for ($i = 0; $i < 6; $i++) {
echo "<tr>";
for ($j = 0; $j < 9; $j++)
echo $artikli[$i * 9 + $j]->get_html();
echo "</tr>";
}
}

How can I make Pagination throw csv file in PHP?

I have a csv file with some data inside.
When User type something in the search bar,it will return the relate data but these results are too much, I want to make a pagination.I don't have any idea, google a lot but can't find a way to do. Please help.
$filename = "Database.csv";
$delimiter = ",";
if (!file_exists($filename) || !is_readable($filename))
return false;
if ($delimiter == ',') {
$csv = array_map('str_getcsv', file($filename));
} else {
$lines = file($filename);
$line_num = count($lines);
$dm = [];
$csv = array_map('str_getcsv', $lines, array_pad($dm, $line_num, $delimiter));
}
array_walk($csv, function (&$row) use ($csv) {
$row = array_combine($csv[0], $row);
});
array_shift($csv);
$total_row_of_csv = count($csv);
$total_row = 0;
for ($i = 0; $i < $total_row_of_csv; $i++) {
if (preg_match("/$value/i", $csv[$i]['Catagory'])) {
echo "<tr>";
echo "<td>" . $csv[$i]['Ref'] . "</td>";
echo "<td>" . $csv[$i]['Catagory'] . "</td>";
echo "<td>" . $csv[$i]['JobTitle'] . "</td>";
echo "<td>" . $csv[$i]['Description'] . "</td>";
echo "<td>" . $csv[$i]['Salary'] . "</td>";
echo "<td>" . $csv[$i]['Nature'] . "</td>";
echo "</tr>";
$total_row++;
}
}
GET : index.php?page=2&search=purchasing
clear the page=1 for a new search
This function is done with get method not post, you can do it as the post by doing appropriately
<?php
// you can make this as post as you want
// i have made this as a get param function
$value = !empty($_GET['search']) ? $_GET['search'] : '';
$filename = "Database.csv";
$delimiter = ",";
if (!file_exists($filename) || !is_readable($filename))
return false;
if ($delimiter == ',') {
$csv = array_map('str_getcsv', file($filename));
} else {
$lines = file($filename);
$line_num = count($lines);
$dm = [];
$csv = array_map('str_getcsv', $lines, array_pad($dm, $line_num, $delimiter));
}
array_walk($csv, function (&$row) use ($csv) {
$row = array_combine($csv[0], $row);
});
array_shift($csv);
$total_row_of_csv = count($csv);
$countForPage = 0;
for ($i = 0; $i < $total_row_of_csv; $i++) {
//var_dump($csv[$i]['Catagory']);die();
// didint get the $value so commented id
if (preg_match("/$value/i", $csv[$i]['Catagory'])) {
$countForPage ++;
}
}
$countForPage;
$numPerPage = 10;
$numCurrPage = !empty($_GET['page']) ? $_GET['page'] : 1;
$numFromCnt = $numPerPage * ($numCurrPage - 1);
$numLastCnt = $numFromCnt + $numPerPage ;
$total_row = 0;
echo "<table>";
for ($i = 0; $i < $total_row_of_csv; $i++) {
//var_dump($csv[$i]['Catagory']);die();
// didint get the $value so commented id
if (preg_match("/$value/i", $csv[$i]['Catagory'])) {
//echo $total_row .">=". $numFromCnt ."&&". $total_row ."<". $numLastCnt; //die();
if($total_row >= $numFromCnt && $total_row < $numLastCnt) {
echo "<tr>";
echo "<td>" . $csv[$i]['Ref'] . "</td>";
echo "<td>" . $csv[$i]['Catagory'] . "</td>";
echo "<td>" . $csv[$i]['JobTitle'] . "</td>";
echo "<td>" . $csv[$i]['Description'] . "</td>";
echo "<td>" . $csv[$i]['Salary'] . "</td>";
echo "<td>" . $csv[$i]['Nature'] . "</td>";
echo "</tr>";
}
$total_row++;
}
}
//echo $total_row;die();
echo "</table>";
$links = generateLinks($countForPage, $numCurrPage, $numPerPage, $value);
echo $links;
function generateLinks($total_row_of_csv, $numCurrPage, $numPerPage, $search){
$pagLink = '';
if($numCurrPage > 1) {
$pagLink .= "<li class='active'><a href='csv_pagination.php?page="
.($numCurrPage-1)."&search=".$search."'>Prev</a></li>";
}
// for ($i=1; $i<=$total_row_of_csv; $i++) {
// if ($i==$numCurrPage) {
// $pagLink .= "<li class='active'><a href='csv_pagination.php?page="
// .$i."'>".$i."</a></li>";
// } else {
// $pagLink .= "<li><a href='csv_pagination.php?page=".$i."'>
// ".$i."</a></li>";
// }
// }
if($numCurrPage < ($total_row_of_csv/$numPerPage)) {
$pagLink .= "<li class='active'><a href='csv_pagination.php?page="
.($numCurrPage+1)."&search=".$search."'>Next</a></li>";
}
return $pagLink;
}
?>

How to add a PHP Variable into HTML code

So I am trying to make a multiplication table and have run into this issue :
<?php
$table = '';
if ($_POST) {
$table .= '<table border="1">';
for ($i = 0; $i < $_POST['qty_line']; $i++) {
$table .= '<tr>';
for ($j = 0; $j < $_POST['qty_column']; $j++) {
$val = $i * $j;
$table .= '<td width="50"> VARIABLE GOES HERE </td>';
}
$table .= '</tr>';
}
$table .= '</table>';
}
?>
Sorry if this is a very simple question but I can't find a solution after searching. Basically i want to insert the $val variable into where it says "VARIABLE GOES HERE" on that specific table data cell. How would I go about this?
You could use
$table .= '<td width="50">' . $val . '</td>';
See the documentation for more examples.

Incorrect output when calculating totals

I have a web page where i am able to export a .csv file that is readable on excel. The invoice pulls the data from my database to calculate the total and grand total using the following columns:
quantity, packing_price, courier_price
I have noticed that my code doesn't output the correct answer when the prices contains a '£' sound in front of it. Is there a way that i could make this work for both number and currency data types?
CODE:
$output2= "";
$sql2 = mysql_query("
SELECT j.date
, j.order_ref
, j.quantity
, j.packing_price
, j.dispatch_type
, j.courier_price
FROM Jobs j
WHERE j.order_type = 'Retail International'
AND j.confirmed = 'Yes';
");
$columns_total2 = mysql_num_fields($sql2);
$total3 = "Total";
for ($i = 0; $i < $columns_total2; $i++)
{
$heading2 = mysql_field_name($sql2, $i);
$output2 .= '"'.$heading2.'",';
}
$output2 .= $total3;
$output2 .="\n";
$sum2 = 0;
while ($row = mysql_fetch_array($sql2)) {
for ($i = 0; $i < $columns_total2; $i++) {
$output2 .='"'.$row["$i"].'",';
}
$qty2 = $row['quantity'];
$pack_price2 = $row['packing_price'];
$dispatch2 = $row['courier_price'];
$total2 = (($qty2*$pack_price2) + $dispatch2);
$total3 = $total2*1.2;
$output2 .= $total3;
$sum2 += $total3; // Add to overall total
$output2 .="\n";
}
Output:
http://i754.photobucket.com/albums/xx182/rache_R/Screenshot2014-07-03at113133_zpsbcc09900.png
Use this Code....
$output= "<table border='1' width='60%'><tr>";
$sql = " SELECT j.date ,
j.order_ref ,
j.quantity ,
j.packing_price ,
j.dispatch_type ,
j.courier_price
FROM Jobs j
WHERE j.order_type = 'Retail International'
AND j.confirmed = 'Yes' ";
$query = mysql_query($sql);
$total_columns = mysql_num_fields($query);
for ($i = 0; $i < $total_columns; $i++){
$heading = mysql_field_name($query, $i);
$output .= '<td>' . $heading . '</td>';
if(($i+1) == $total_columns) $output .= '<td>Total</td></tr>';
}
while ($row = mysql_fetch_array($query)) {
$total_price = 0;
$total_price =( ( $row['quantity'] * $row['packing_price'] ) +
$row['courier_price'] );
$total_price = $total_price * 1.2;
$timestamp = DateTime::createFromFormat('Y-m-d h:i:s',
$row['date'])->getTimestamp();
$output .= '<tr>';
$output .= '<td>' . date("d/m/Y", $timestamp) . '</td>';
$output .= '<tr>';
$output .= '<td>' . date("d/m/Y", strtotime($row['date']) . '</td>';
$output .= '<td>' . $row['order_ref'] . '</td>';
$output .= '<td>' . $row['quantity']. '</td>';
$output .= '<td>' . $row['packing_price'] . '</td>';
$output .= '<td>' . $row['dispatch_type'] . '</td>';
$output .= '<td>' . $row['courier_price'] . '</td>';
$output .= '<td>' . number_format($total_price, 2) . '</td>';
$output .= '</tr>';
}
$output .= "</table>";
echo '<br>' . $output;

PHP Sorting files in a table

Currently I have a table order by
A B C D
E F G H
but I would like to order the table by
A E
B F
C G
D H
Code:
for($i=0;$i<=count($aFiles);$i++)
{
if($i%5==0)
{
echo "</tr><tr>";
}
echo '<td><a>'.$aFiles[$i].'</a></td>';
}
echo '</tr>';
echo '</table>';
Files are already sorted a-z in $aFiles.
$aFiles = array('a','b','c','d', 'e', 'f', 'g');
$iColumnNumber = 2;
$iRowMaxNumber = ceil(count($aFiles) / $iColumnNumber);
$iTableRow = 0;
$iTableColumns = 1;
$aTableRows = array();
// make array with table cells
foreach ($aFiles as $sFile)
{
if ($iTableRow == $iRowMaxNumber)
{
$iTableRow = 0;
$iTableColumns++;
}
if (!isset($aTableRows[$iTableRow]))
{
$aTableRows[$iTableRow] = array();
}
$aTableRows[$iTableRow][] = '<td>' . $sFile . '</td>';
$iTableRow++;
}
// if there is odd number of elements
// we should add empty td elements
for ($iTableRow; $iTableRow < $iRowMaxNumber; $iTableRow++)
{
if (count($aTableRows[$iTableRow]) < $iTableColumns)
{
$aTableRows[$iTableRow][] ='<td>empty</td>';
}
}
// display table
echo '<table>';
foreach ($aTableRows as $aTableRow)
{
echo '<tr>';
echo implode('', $aTableRow);
echo '</tr>';
}
echo '</table>';
Simple Approach using HTML trick:
echo '<div class="tbl_group"><table>';
for($i=0;$i<=count($aFiles / 2);$i++)
{
echo '<tr>';
echo '<td><a>'.$aFiles[$i].'</a></td>';
echo '</tr>';
}
echo '</tr>';
echo '</table></div>';
echo '<div class="tbl_group"><table>';
for($i=$aFiles / 2;$i<=count($aFiles);$i++)
{
echo '<tr>';
echo '<td><a>'.$aFiles[$i].'</a></td>';
echo '</tr>';
}
echo '</tr>';
echo '</table></div>';
For the CSS:
.tbl_group {
float: left;
}
With this approach, 2 tables are built side-by-side. float: left CSS will auto adjust the position of the tables.
Assuming you know the number of rows you want, you don't need to resort anything, just add some logic in your loop that generates the <td>s :
$size = count($aFiles);
echo '<table><tr>';
for($i=0;$i<=ceil($size/2);$i++) {
if($i%2==0) {
echo '<td><a>'.$aFiles[$i].'</a></td>';
echo "</tr><tr>";
} else {
if(isset($aFiles[$i+floor($size/2)])) {
echo '<td><a>'.$aFiles[$i+floor($size/2)].'</a></td>';
}
}
}
echo '</tr></table>';
Example bellow also works with associative array + arrays with odd elements.
Code for associative AND indexed array :
$aFiles = ['test'=>"A","B",'c'=>"C","D","E","F",'g'=>"G","H",'iii'=>"I"];
$aKeys = array_keys($aFiles);
$aRows = ceil(count($aFiles) / 2);
echo '<table>';
for($i=0; $i < $aRows; $i++) {
echo
'<tr>' .
' <td>' . $aFiles[$aKeys[$i]] . '</td>' .
' <td>' . (isset($aKeys[$i+$aRows]) ? $aFiles[$aKeys[$i+$aRows]] : 'empty') . '</td>' .
'</tr>';
}
echo '</table>';
Code for ONLY indexed array :
$aFiles = ["A","B","C","D","E","F","G","H","I"];
$aRows = ceil(count($aFiles) / 2);
echo "<table>";
for($i=0; $i < $aRows; $i++) {
echo
"<tr>" .
" <td>" . $aFiles[$i] . "</td>" .
" <td>" . (isset($aFiles[$i+$aRows]) ? $aFiles[$i+$aRows] : "empty") . "</td>" .
"</tr>";
}
echo "</table>";
Output for both examples is identical :
<table>
<tr>
<td>A</td>
<td>F</td>
</tr>
<tr>
<td>B</td>
<td>G</td>
</tr>
<tr>
<td>C</td>
<td>H</td>
</tr>
<tr>
<td>D</td>
<td>I</td>
</tr>
<tr>
<td>E</td>
<td>empty</td>
</tr>
</table>
Not optimized, but this should more or less work:
$aFiles = array ("A","B","C","D","E","F","G","H","I","J","K","L","M","N",);
$rows = 4;
$columns = floor((count($aFiles)/$rows))+1;
echo '<table>';
for ($i=0;$i<$rows;$i++) {
echo '<tr>';
for ($j=0;$j<$columns;$j++) {
echo '<td>';
if (isset($aFiles[$i+$j*$rows]))
echo $aFiles[$i+$j*$rows];
else
echo " ";
echo '</td>';
}
echo '</tr>';
}
echo '</table>';
You can change the number of rows if you want.
Try this one. Assume that your $aFiles contains a-z alphabetically.
for ($i = 0; $i < count($aFiles/2); $i++){
echo '<tr><td><a>'.$aFiles[$i].'</a><td><td><a>'.$aFiles[$i+13].'</a><td></tr>'
}

Categories