Displaying Rows of HTML Elements in Vertical Rows - php

I want to show a list of categories in my Virtuemart webshop vertically sorted the same way as shown in this demonstration:
http://www.inkplant.com/code/mysql-vertical-sort.php
So I borrowed the code:
<?php
$cols = 4; //number of columns, you can set this to any positive integer
$values = array();
$result = mysql_query("SELECT * FROM states ORDER BY name");
$numrows = mysql_num_rows($result);
$rows_per_col = ceil($numrows / $cols);
for ($c=1;$c<=$cols;$c++) { $values['col_'.$c] = array(); }
$c = 1;
$r = 1;
while ($row = mysql_fetch_assoc($result)) {
$values['col_'.$c][$r] = stripslashes($row['name']);
if ($r == $rows_per_col) { $c++; $r = 1; } else { $r++; }
}
echo "<table>" ;
for ($r=1;$r<=$rows_per_col;$r++) {
echo "<tr>" ;
for ($c=1;$c<=$cols;$c++) { echo "<td>".$values['col_'.$c][$r]."</td>" ; }
echo "</tr>" ;
}
echo "</table>" ;
unset($values);
?>
I then tried to modify it in my Virtuemart category template file with this result:
<?php
$cols = 3; //number of columns, you can set this to any positive integer
$values = array();
$numrows = $precounterdigit;
$rows_per_col = ceil($numrows / $cols);
for ($c=1;$c<=$cols;$c++) { $values['col_'.$c] = array(); }
$c = 1;
$r = 1;
foreach ( $this->category->children as $category ) {
$catname = $category->category_name;
$caturl = JRoute::_ ( 'index.php?option=com_virtuemart&view=category&virtuemart_category_id=' . $category->virtuemart_category_id );
$values['col_'.$c][$r] = '<div class="category floatleft'.$category_cellwidth.'">
<div class="spacer"><h2>
<a href="'.$caturl.'" title="'.$catname.'">
'.$catname.'<br /></a></h2>
</div></div>';
if ($r == $rows_per_col) { $c++; $r = 1; } else { $r++; }
}
echo '<div class="tablediv">' ;
for ($r=1;$r<=$rows_per_col;$r++) {
echo '<div class="row">' ;
for ($c=1;$c<=$cols;$c++) { echo $values['col_'.$c][$r]; }
echo '</div>' ;
}
echo '</div>' ;
unset($values);
?>
It actually shows perfectly in the category view if the number of categories are dividable by 3 or dividable by 3 -1. Meaning that it shows correctly if there are 3, 5, 6, 8, 9, 11, 12 etc... categories on the page.
If the number of categories equals a number that is dividable by 3 +1 then it shows in a weird way..
Here is an example of how it shows when there are 9 categories:
Cat1 | Cat4 | Cat7
Cat2 | Cat5 | Cat8
Cat3 | Cat6 | Cat9
Here is an example of how it shows when there are 8 categories:
Cat1 | Cat4 | Cat7
Cat2 | Cat5 | Cat8
Cat3 | Cat6 |
And here is an example of how it shows when there are 7 categories:
Cat1 | Cat4 | Cat7
Cat2 | Cat5 | Cat3
Cat6 |
I really cannot figure this one out, so I hope someone can help me a little bit here..

Just try this, Sure you can change cols and rows.
<?php //user210424
$cols = 3;
$rows = 3;
$j = 0;
$array = array("ONE","TWO","THREE","FOUR","FIVE","SIX","SEVEN","EIGHT","NINE");
for($i=1; $i<=$cols; $i++) {
echo "<div class='col' style='float:left;'>";
for($j; $j<$rows*$i; $j++) {
echo "<div class='row'>".$array[$j]."</div>";
}
echo "</div>";
}
?>

Related

Reading and writing a text file with the results of tournament matches with PHP

Group G of The Champions League the results of football competition:
RB Leipzig;AS Monaco;draw
FC Porto;Besiktas JK;loss
Besiktas JK;RB Leipzig;win
AS Monaco;FC Porto;loss
AS Monaco;Besiktas JK;loss
RB Leipzig;FC Porto;win
Besiktas JK;AS Monaco;draw
FC Porto;RB Leipzig;win
Besiktas JK;FC Porto;draw
AS Monaco;RB Leipzig;loss
FC Porto;AS Monaco;win
RB Leipzig;Besiktas JK;loss
The result of the match refers to the first team listed.
(Examples:
Besiktas JK;RB Leipzig;win
means that the Besiktas JK beat the RB Leipzig.
AS Monaco FC;Besiktas JK;loss
means that the Besiktas beat the AS Monaco FC.
RB Leipzig;AS Monaco FC;draw
means that the RB Leipzig and AS Monaco FC tied.)
A win earns a team 3 points. A draw earns 1. A loss earns 0.
The outcome should be ordered by points, descending. In case of a tie, teams are ordered alphabetically.
The output should come out like this:
Team | MP | W | D | L | P
Besiktas JK | 6 | 4 | 2 | 0 | 14
FC Porto | 6 | 3 | 1 | 2 | 10
RB Leipzig | 6 | 2 | 1 | 3 | 6
AS Monaco | 6 | 0 | 2 | 4 | 2
However, I can't get the results in terms of rankings and away wins. How can I do it?
#tournament.txt
RB Leipzig;AS Monaco;draw
FC Porto;Besiktas JK;loss
Besiktas JK;RB Leipzig;win
AS Monaco;FC Porto;loss
AS Monaco;Besiktas JK;loss
RB Leipzig;FC Porto;win
Besiktas JK;AS Monaco;draw
FC Porto;RB Leipzig;win
Besiktas JK;FC Porto;draw
AS Monaco;RB Leipzig;loss
FC Porto;AS Monaco;win
RB Leipzig;Besiktas JK;loss
#tournament.php
<?php
$lines = file('tournament.txt');
foreach ($lines as $line) {
$parts = explode(';', $line);
$teams[$parts[0]][] = $parts[2];
$teams[$parts[1]][] = $parts[2];
}
uksort($teams, function ($a, $b) use ($teams) {
$aPoints = 0;
$bPoints = 0;
foreach ($teams[$a] as $result) {
if ($result == 'win') {
$aPoints += 3;
} elseif ($result == 'draw') {
$aPoints += 1;
}
}
foreach ($teams[$b] as $result) {
if ($result == 'win') {
$bPoints += 3;
} elseif ($result == 'draw') {
$bPoints += 1;
}
}
foreach ($teams[$a] as $result) {
if ($result == 'loss') {
$aPoints += 0;
$bPoints += 3;
}
}
foreach ($teams[$b] as $result) {
if ($result == 'loss') {
$aPoints += 3;
$bPoints += 0;
}
}
if ($aPoints == $bPoints) {
return $a <=> $b;
}
return $bPoints <=> $aPoints;
});
$fp = fopen('tournament.txt', 'w');
fwrite($fp, "Team | MP | W | D | L | P
");
foreach ($teams as $team => $results) {
$mp = count($results);
$w = 0;
$d = 0;
$l = 0;
foreach ($results as $result) {
if ($result == 'win') {
$w++;
} elseif ($result == 'draw') {
$d++;
} else {
$l++;
}
}
$p = $w * 3 + $d;
fwrite($fp, sprintf("%-30s| %2d | %2d | %2d | %2d | %2d
", $team, $mp, $w, $d, $l, $p));
}
fclose($fp);
?>
I cannot test your code because I am in PHP Version 5.6.36.
But with the code below which works from PHP 5 I get results.
Including away wins.
<style type="text/css">
table { border-spacing: 0px; }
table th { padding: 5px; border: 1px solid black; }
table td { padding: 3px; border: 1px solid dimgrey; }
</style>
<?
// Initialisation
$infoList = array("MP","W","Wext","D","L","P");
// Open File
$lines = file('tournament.txt');
// For Each Line
foreach ($lines as $line)
{
$parts = explode(';', $line);
// Extraction
$teamA = $parts[0];
$teamB = $parts[1];
$score = $parts[2];
// Initialization
$teamList["$teamA"]["W"] = 0;
$teamList["$teamA"]["Wext"] = 0;
$teamList["$teamA"]["L"] = 0;
$teamList["$teamA"]["D"] = 0;
$teamList["$teamA"]["P"] = 0;
$teamList["$teamA"]["MP"] = (array_key_exists("MP", $teamList["$teamA"]))?bcadd($teamList["$teamA"]["MP"],1,0):1;
// Initialization
$teamList["$teamB"]["W"] = 0;
$teamList["$teamB"]["Wext"] = 0;
$teamList["$teamB"]["L"] = 0;
$teamList["$teamB"]["D"] = 0;
$teamList["$teamB"]["P"] = 0;
$teamList["$teamB"]["MP"] = (array_key_exists("MP", $teamList["$teamB"]))?bcadd($teamList["$teamB"]["MP"],1,0):1;
// Memorisation
$matchList[] = array("teamA"=>$teamA, "teamB"=>$teamB, "score"=>trim($score));
}
// End - For Each Line
// For Each Match
foreach($matchList as $matchKey => $matchValue)
{
// If Team A Win
if($matchValue["score"]=="win")
{
// Memorisation Team A
$teamList["".$matchValue["teamA"].""]["W"] = bcadd($teamList["".$matchValue["teamA"].""]["W"],1,0);
$teamList["".$matchValue["teamA"].""]["P"] = bcadd($teamList["".$matchValue["teamA"].""]["P"],3,0);
}
// If Team A Loss
if($matchValue["score"]=="loss")
{
// Memorisation Team B
$teamList["".$matchValue["teamB"].""]["W"] = bcadd($teamList["".$matchValue["teamB"].""]["W"],1,0);
$teamList["".$matchValue["teamB"].""]["Wext"] = bcadd($teamList["".$matchValue["teamB"].""]["Wext"],1,0);
$teamList["".$matchValue["teamB"].""]["P"] = bcadd($teamList["".$matchValue["teamB"].""]["P"],3,0);
}
// If Equality
if($matchValue["score"]=="draw")
{
// Memorisation Team A
$teamList["".$matchValue["teamA"].""]["D"] = bcadd($teamList["".$matchValue["teamA"].""]["D"],1,0);
$teamList["".$matchValue["teamA"].""]["P"] = bcadd($teamList["".$matchValue["teamA"].""]["P"],1,0);
// Memorisation Team B
$teamList["".$matchValue["teamB"].""]["D"] = bcadd($teamList["".$matchValue["teamB"].""]["D"],1,0);
$teamList["".$matchValue["teamB"].""]["P"] = bcadd($teamList["".$matchValue["teamB"].""]["P"],1,0);
}
}
// Fin - For Each Match
// -------- Display in HTML -------- //
echo "<table>";
echo "<tr>";
echo "<th></th>";
foreach($infoList as $infoKey => $infoValue) { echo "<th>".$infoValue."</th>"; }
echo "</tr>";
// For Each Team
foreach($teamList as $teamName => $teamValue)
{
echo "<tr>";
echo "<td>".$teamName."</td>";
// For Each Type Information
foreach($infoList as $infoKey => $infoValue)
{
echo "<td>".$teamValue["$infoValue"]."</td>";
}
// End - For Each Type Information
echo "</tr>";
}
// End - For Each Team
echo "</table>";
// --------------------------------- //
?>
It may seem a bit heavy but it allows to have a teamList array with all the necessary information

Building html table using php

I am looking to have a table built using php but with a twist. I want to only limit it to 10 rows. If the variable is greater than 10, then a new column is added. IE:
If the variable is 9 then the table will have 1 column and 9 rows. If the number is 19 then the table will contain 10 rows and 2 columns with the second columns containing numbers 11 - 19. And so on Similar to below
+----+-------+-------+----+-------+-------+----+-------+-------+
| Q | Tally | Total | Q | Tally | Total | Q | Tally | Total |
+----+-------+-------+----+-------+-------+----+-------+-------+
| 1 | | | 11 | | | 21 | | |
+----+-------+-------+----+-------+-------+----+-------+-------+
| 2 | | | 12 | | | 22 | | |
+----+-------+-------+----+-------+-------+----+-------+-------+
| 3 | | | 13 | | | 23 | | |
+----+-------+-------+----+-------+-------+----+-------+-------+
| 4 | | | 14 | | | 24 | | |
+----+-------+-------+----+-------+-------+----+-------+-------+
| 5 | | | 15 | | | 25 | | |
+----+-------+-------+----+-------+-------+----+-------+-------+
| 6 | | | 16 | | | | | |
+----+-------+-------+----+-------+-------+----+-------+-------+
| 7 | | | 17 | | | | | |
+----+-------+-------+----+-------+-------+----+-------+-------+
| 8 | | | 18 | | | | | |
+----+-------+-------+----+-------+-------+----+-------+-------+
| 9 | | | 19 | | | | | |
+----+-------+-------+----+-------+-------+----+-------+-------+
| 10 | | | 20 | | | | | |
+----+-------+-------+----+-------+-------+----+-------+-------+
Any idea how I can achieve this?
I have gotten this far
$table_string = 'Table Name 1:45,Table Name 2:20,Table Name 3:9';
function foo()
{
$tables = explode(',', $table_string);
$output = '';
foreach ($tables as $table)
{
$table_name = explode(':', $table)[0];
$table_rows = explode(':',$table)[1];
$table_columns = ceil($table_rows/10);
$output .= "<br>
<table class='table table-bordered table-small'>
<tr>
<th scope='col' colspan='99'>{$table_name}</th>
</tr>";
for ($x = 1; $x <=10; $x++)
{
$output .= "<tr>";
for ($y = 1; $y <= $table_columns * 3; $y++)
{
if ($y % 3 == 1) {
$output .= "<td scope=\"col\">Q</td>";
} else if ($y % 3 == 2) {
$output .= "<td scope=\"col\">Tally</td>";
} else {
$output .= "<td scope=\"col\">Total</td>";
}
}
$output .= "</tr>";
$output .= "<tr>";
for ($y = 1; $y <= $table_columns * 3; $y++)
{
if ($y == 1 || $y % 4 == 0) {
$z = ceil($y / 4);
$output .= "<td scope=\"row\">{$z}</td>";
} else {
$output .= "<td></td>";
}
}
$output .= "</tr>";
}
$output .= "</table>";
}
return $output;
}
To help answer the question more: Here is the current output I get:
+---+-------+-------+---+-------+-------+---+-------+-------+---+-------+-------+---+-------+-------+
| Q | Tally | Total | Q | Tally | Total | Q | Tally | Total | Q | Tally | Total | Q | Tally | Total |
+---+-------+-------+---+-------+-------+---+-------+-------+---+-------+-------+---+-------+-------+
| 1 | | | 1 | | | | 2 | | | | 3 | | | |
+---+-------+-------+---+-------+-------+---+-------+-------+---+-------+-------+---+-------+-------+
| 1 | | | 1 | | | | 2 | | | | 3 | | | |
+---+-------+-------+---+-------+-------+---+-------+-------+---+-------+-------+---+-------+-------+
| 1 | | | 1 | | | | 2 | | | | 3 | | | |
+---+-------+-------+---+-------+-------+---+-------+-------+---+-------+-------+---+-------+-------+
| 1 | | | 1 | | | | 2 | | | | 3 | | | |
+---+-------+-------+---+-------+-------+---+-------+-------+---+-------+-------+---+-------+-------+
| 1 | | | 1 | | | | 2 | | | | 3 | | | |
+---+-------+-------+---+-------+-------+---+-------+-------+---+-------+-------+---+-------+-------+
| 1 | | | 1 | | | | 2 | | | | 3 | | | |
+---+-------+-------+---+-------+-------+---+-------+-------+---+-------+-------+---+-------+-------+
| 1 | | | 1 | | | | 2 | | | | 3 | | | |
+---+-------+-------+---+-------+-------+---+-------+-------+---+-------+-------+---+-------+-------+
| 1 | | | 1 | | | | 2 | | | | 3 | | | |
+---+-------+-------+---+-------+-------+---+-------+-------+---+-------+-------+---+-------+-------+
| 1 | | | 1 | | | | 2 | | | | 3 | | | |
+---+-------+-------+---+-------+-------+---+-------+-------+---+-------+-------+---+-------+-------+
| 1 | | | 1 | | | | 2 | | | | 3 | | | |
+---+-------+-------+---+-------+-------+---+-------+-------+---+-------+-------+---+-------+-------+
Try this code :
//no. of ques
$total_ques = 45;
//creating array for que no
$que_nos = range(1,(int)$total_ques);
$part = 10;
//splitting array in chunks
$cols = array_chunk($que_nos,$part);
echo '<table border="1" cellpadding="5">';
echo '<tr>';
foreach($cols as $col) {
//Generating heading columns
echo "<td>Q</td>";
echo "<td>Tally</td>";
echo "<td>Total</td>";
}
echo '</tr>';
//data for each row
$row_data = [];
for ($i=0; $i < $part; $i++) {
//temporary variable containing values for each row
$temp_row_data = [];
foreach($cols as $k1 => $col) {
//getting first value of array
$value = reset($col);
$temp_row_data[] = $value ?: '';
if ($value !== false) {
//unset value as it is already processed
unset($cols[$k1][array_search($value,$col)]);
}
}
//storing temporary array in main row array
$row_data[] = $temp_row_data;
}
foreach ($row_data as $key => $cd) {
echo '<tr>';
foreach ($cd as $c) {
echo "<td>{$c}</td>";
echo "<td></td>";
echo "<td></td>";
}
echo '</tr>';
}
echo '</table>';
Demo
The output will be like as below in the image
1.You should calculate count of columns:
if a count of records is multiple of ten then count of columns is equal count of records / 10 otherwise count of columns is equal count of records / 10 + 1. Code example:
$rowCount = 10;
$colCount = intval($recordCount / $rowCount);
if ($recordCount % $rowCount !== 0 ) {
$colCount++;
}
2.You should calculate index of a row in the table for each element and build array of table rows. This index can be calculated with help the following formula: index of an element % count of rows. Count example:
$rows = [];
for ($i = 0; $i < $recordCount; $i++) {
$index = $i % $rowCount;
$rows[$index][] = [
'Q' => $i+1,
'Tally' => '', // you can set value
'Total' => '', // you can set value
];
}
As can you see this algorithm is very simple and its asymptotic complexity is O(n)
3.You should render header with help count of columns. Code example:
$output .= '<tr>';
for ($i = 1; $i <= $colCount; $i++) {
$output .= '<td scope="col">Q</td>
<td scope="col">Tally</td>
<td scope="col">Total</td>';
}
$output .= '</tr>';
4.You should render other parts of a table with help array of table rows. Code example:
foreach ($rows as $row) {
$output .= '<tr>';
foreach ($row as $element) {
$output .= "<td>{$element['Q']}</td><td></td><td></td>";
}
$output .= '</tr>';
}
Full code:
function buildTable($name, $rowCount, $recordCount)
{
//calculating of count rows
$colCount = intval($recordCount / $rowCount);
if ($recordCount % $rowCount !== 0 ) {
$colCount++;
}
// making of row array
$rows = [];
for ($i = 0; $i < $recordCount; $i++) {
$index = $i % $rowCount;
$rows[$index][] = [
'Q' => $i+1,
'Tally' => '', // you can set value
'Total' => '', // you can set value
];
}
// render header
$output = "<table class='table table-bordered table-small'>
<tr>
<th scope='col' colspan='99'>{$name}</th>
</tr>";
$output .= '<tr>';
for ($i = 1; $i <= $colCount; $i++) {
$output .= '<td scope="col">Q</td>
<td scope="col">Tally</td>
<td scope="col">Total</td>';
}
$output .= '</tr>';
// render other parts of table
foreach ($rows as $row) {
$output .= '<tr>';
foreach ($row as $element) {
$output .= "<td>{$element['Q']}</td><td></td><td></td>";
}
$output .= '</tr>';
}
$output .= "</table>";
return $output;
}
$tablename = 'test';
$recordCount = 25;
$rowCount = 10;
echo buildTable($tablename, $rowCount, $recordCount);
Forgive me if I over complicated things, but I tried to approach this a little bit different :)
interface DrawableTable
{
public function draw ();
}
class Table implements DrawableTable
{
const MAX_ALLOWED_ROWS = 10;
protected $name;
protected $rows;
protected $cols;
/**
* #var TableHeaderContract $header
*/
protected $header;
/**
* #var TableBodyContract $body
*/
protected $body;
public function __construct ($name, $rows, $cols)
{
$this->name = $name;
$this->rows = $rows;
$this->cols = $cols;
$this->header = new TableHeader(ceil($this->cols / self::MAX_ALLOWED_ROWS), ['Q', 'Tally', 'Total']);
$this->body = new TableBody(self::MAX_ALLOWED_ROWS);
//Here I am adding random numbers but you can call body and add as you need them!
for ($randI = 1; $randI <= $this->cols; $randI++) {
$this->body->addRow(new Row($randI, '', ''));
}
}
public function draw ()
{
return (new TableMarshaller)($this);
}
/**
* #return mixed
*/
public function getName ()
{
return $this->name;
}
/**
* #return mixed
*/
public function getRows ()
{
return $this->rows;
}
/**
* #return mixed
*/
public function getCols ()
{
return $this->cols;
}
/**
* #return TableHeaderContract
*/
public function getHeader ()
{
return $this->header;
}
/**
* #return TableBodyContract
*/
public function getBody ()
{
return $this->body;
}
}
interface TableHeaderContract
{
public function drawHeaders ();
}
class TableHeader implements TableHeaderContract
{
protected $repetitions;
protected $headers = [];
public function __construct ($repetitions, $headers = [])
{
$this->repetitions = $repetitions;
$this->addHeadersAccordingToRows($headers);
}
private function addHeadersAccordingToRows ($headers)
{
for ($iteration = 0; $iteration < $this->repetitions; $iteration++) {
$this->headers = array_merge($this->headers, $headers);
}
}
/**
* #return array
*/
public function getHeaders ()
{
return $this->headers;
}
public function drawHeaders ()
{
return (new HeaderThreeMarshaller)($this);
}
}
class Row
{
protected $id;
protected $tally;
protected $total;
public function __construct ($id, $tally, $total)
{
$this->id = $id;
$this->tally = $tally;
$this->total = $total;
}
/**
* #return mixed
*/
public function getId ()
{
return $this->id;
}
/**
* #param mixed $id
*
* #return Row
*/
public function setId ($id)
{
$this->id = $id;
return $this;
}
/**
* #return mixed
*/
public function getTally ()
{
return $this->tally;
}
/**
* #param mixed $tally
*
* #return Row
*/
public function setTally ($tally)
{
$this->tally = $tally;
return $this;
}
/**
* #return mixed
*/
public function getTotal ()
{
return $this->total;
}
/**
* #param mixed $total
*
* #return Row
*/
public function setTotal ($total)
{
$this->total = $total;
return $this;
}
}
interface TableBodyContract
{
public function drawBody ();
}
class TableBody implements TableBodyContract
{
protected $allowedRowSize;
/**
* #var array $rows Multi Dimentional array!
*/
protected $rows = [];
public function __construct ($maxRowSize)
{
$this->allowedRowSize = $maxRowSize;
}
public function addRow (Row $row)
{
//$this->rows[(int)(floor($row->getId() % 10))][] = $row;
//Makes sure to instanciate all allowed rows
if (count($this->rows) < $this->allowedRowSize) {
$this->rows[count($this->rows)][] = $row;
return $this;
}
for ($i = 0; $i < count($this->rows); $i++) {
if (array_key_exists($i + 1, $this->rows)) {
// if current have euqal or less values than the next, means we need to add it here!
if (count($this->rows[$i]) < count($this->rows[($i + 1)])) {
$this->rows[$i][] = $row;
return $this;
} else if (count($this->rows[$i]) <= count($this->rows[count($this->rows) - 1])) {
$this->rows[$i][] = $row;
return $this;
}
continue;
}
}
$this->rows[count($this->rows) - 1][] = $row;
return $this;
}
/**
* #return array
*/
public function getRows ()
{
return $this->rows;
}
public function drawBody ()
{
return (new BodyMarshaller)($this);
}
}
/**
* MARSHALLERS TO PARSE TO YOUR VIEW
*/
class TableMarshaller
{
/**
* #var Table $table
*/
protected $table;
protected $htmlOutput;
public function __invoke (Table $table)
{
$this->table = $table;
//Wrap table into a div
$this->htmlOutput = '<div>';
//Table -> Name
$this->attachTableName();
//Table -> Header and Body
$this->attachTableContent();
$this->htmlOutput .= '</div>';
return $this->htmlOutput;
}
private function attachTableName ()
{
$this->htmlOutput .= sprintf('<h2>%s</h2>', $this->table->getName());
}
private function attachTableContent ()
{
$this->htmlOutput .= '<table class="table table-bordered table-small">';
$this->htmlOutput .= $this->table->getHeader()->drawHeaders();
$this->htmlOutput .= $this->table->getBody()->drawBody();
$this->htmlOutput .= '</table>';
}
}
class HeaderThreeMarshaller
{
public function __invoke (TableHeaderContract $tableHeader)
{
$htmlOutput = '<theader>';
foreach ($tableHeader->getHeaders() as $headTitle) {
if (!empty($headTitle)) {
$htmlOutput .= sprintf('<th>%s</th>', $headTitle);
}
}
$htmlOutput .= '</theader>';
return $htmlOutput;
}
}
class BodyMarshaller
{
public function __invoke (TableBodyContract $body)
{
$htmlOutput = '<body>';
foreach ($body->getRows() as $rowNum => $rows) {
$htmlOutput .= '<tr>';
/**
* #var Row $row
*/
foreach ($rows as $row) {
$htmlOutput .= sprintf(
'<td>%d</td><td>%s</td><td>%d</td>',
$row->getId(),
$row->getTally(),
$row->getTotal()
);
}
$htmlOutput .= '</tr>';
}
$htmlOutput .= '</body>';
return $htmlOutput;
}
}
And here is how you can test its generation. So for the example below:
$table = new Table('Test Example 1', 5, 85);
print $table->draw();
You can copy the code example I created and check its output on a HTML file!
You can try the following code:
<?php
// -------- Functions --------
function foo($tables_string)
{
// Decompose tables string
$tables = explode(',', $tables_string);
// Header of the 3 columns
$headers = "<td class='bg_gray' scope='col'>Q</td>"
. "<td class='bg_gray' scope='col'>Tally</td>"
. "<td class='bg_gray' scope='col'>Total</td>";
// Starts output empty
$output = "";
// For each table string
foreach ($tables as $table)
{
// Use of list() to store explode in multiple variables
list($table_name, $table_rows) = explode(':', $table);
// Calculate number of columns
$table_columns = ceil($table_rows/10);
// Starts table
$output .= "<br>
<table class='table table-bordered table-small'>
<tr>
<th scope='col' colspan='99'>{$table_name}</th>
</tr>";
// Use str_repeat() instead of a loop
$output .= "<tr>".str_repeat($headers, $table_columns)."</tr>";
// Loop for trs
for ($x = 1; $x <= 10; $x++)
{
$output .= "<tr>";
// Loop for tds
for ($y = 0; $y < $table_columns * 3; $y++)
{
//z = number of the “row”
$z = (10 * $y / 3) + $x;
// If first column, and not end of our data
if(($y % 3 == 0) && ($z <= $table_rows)){
$output .= "<td scope='row'>{$z}</td>";
} else {
$output .= "<td> </td>";
}
}
// End of table row
$output .= "</tr>";
}
// End of table
$output .= "</table>";
}
return $output;
}
// -------- Main script --------
// Stylize the output
echo "<style>
table { border-collapse: collapse; }
td { padding: 4px 8px; border: 1px solid gray; }
.bg_gray { background: lightgray; }
</style>";
// Use the function above
$tables = 'Table Name 1:45,Table Name 2:20,Table Name 3:9';
echo foo($tables);
?>
… in which I did the following:
Tried to not change much your coding philosophy (because you must want to populate the other columns),
Tried to comment a lot of things for better understanding,
Correct some things, enhance some others (see comments for details),
Added some styling for better visibility of the output.
Tested here, where you can see the output as HTML: http://www.writephponline.com/
Some of the functions I used to simplify:
list
str_repeat
⋅
⋅
⋅

Divide list in three columns

I have list of values that I want to fetch from my database. List could be long so I want to divide into two columns if it has over 15 items and to three columns if it has over 30. How can I break it in 3 columns. Eg..
01 | 12 | 23
02 | 13 | 24
03 | 14 | 25
04 | 15 | 26
05 | 16 | 27
06 | 17 | 28
07 | 18 | 29
08 | 19 | 30
09 | 20 | 31
10 | 21 |
11 | 22 |
For now i'm using tables and it has huge if-nest at the beginning of every loop
$result = mysql_query("SELECT namecount FROM table WHERE name='$myvar'");
if (!$result)
echo 'MySQL Error: ' . mysql_error();
else
{
while ($row = mysql_fetch_array($result))
{
$namecount= $row['namecount'];
for($i=1;$i<=$namecount;$i++)
{
if($namecount>15)
{
if($i==1)
echo "\n<table><tr><td width=\"200px\">";
if($namecount%2==0)
{
if($i==$namecount/2)
echo "</td>\n<td>";
}
else
{
if($i==($sailiot+3)/2)
echo "</td>\n<td>";
}
}
//Print content here
if($namecount>15)
{
if($namecount%2!=0 && $i==$namecount)
echo "<h3> </h3><p> <br> </p>"; //if last item and count is odd, print empty item
if($i==$namecount)
echo "\n</td></tr></table>\n";
}
}
}
}
This (kinda) works with two columns, but what about three?
I would extract <tr>, </tr> out of the inner loop, this saves additional ifs. For splitting into multiple columns, you can calculate the number of items in a column and introduce a second intra column variable to keep track of:
while ($row = mysql_fetch_array($result)) {
$namecount = $row['namecount'];
// calculate items per column
$columns = 1;
if ($namecount > 15)
$columns = 2;
if ($namecount > 30)
$columns = 3;
$items = $namecount / $columns;
if ($namecount % $columns > 0)
++$items;
echo "\n<table><tr><td width=\"200px\">";
for ($i = 1, $j = 1; $i <= $namecount; $i++, $j++) {
if ($j > $items) {
echo "</td>\n<td>";
$j = 1; // reset for new column
}
// Print content here
}
if ($namecount % 2 != 0) {
// if count is odd, print empty item
echo "<h3> </h3><p> <br> </p>";
}
echo "\n</td></tr></table>\n";
}
you maybe can try this
$result = mysql_query("SELECT namecount FROM table WHERE name='$myvar'");
if (!$result)
echo 'MySQL Error: ' . mysql_error();
else
{
while ($row = mysql_fetch_array($result))
{
$namecount= $row['namecount'];
for($i=1;$i<=$namecount;$i++)
{
if($namecount<=15){
echo "<table><thead><tr><th>".$your_variable_data."</th></tr></thead>";}
else if ($namecount >15 and $namecount <=30){
echo "<thead><tr><th>".$your_variable_data."</th></tr></thead></table>";
}
}
}
its not tested but it should work for 3 columns if you want more just add else if .
here a demo how it will be
http://jsfiddle.net/TCJjj/107/
use css3 multi column property
<style>
.namecount {
-moz-column-count:3; /* Firefox */
-webkit-column-count:3; /* Safari and Chrome */
column-count:3;
}
</style>
<div class="namecount">
Long Text
</div>
I found that CSS3 multi-columns was horribly inconsistent between browsers, and very buggy (elements with float:left, white-space:nowrap, etc. cause it to break).
So I wrote the following brute-force collator that retains key=>value pairs.
// vars
$list = array('a','b','c','d','e','f','g','h','i','j','k','l','m',
'n','o','p','q','r','s','t','u','v','w','x','y','z');
$columns = 3;
// sort it
$count = count($list);
$base = ceil($count/$columns);
$keys = array_keys($list);
for ($i=0;$i<$columns;$i++) {
for ($j=0;$j<$base;$j++) {
if (!empty($keys)) {
$col[$i][] = array_shift( $keys );
}
}
}
$sorted = array();
for ($j=0;$j<$base;$j++) {
for ($i=0;$i<$columns;$i++) {
if (isset($col[$i][$j])) {
$sorted[$col[$i][$j]] = $list[$col[$i][$j]];
}
}
}
// check output
echo '<div style="float:left;margin-right:20px"><h3>ORIGINAL</h3>';
foreach ($list as $k=>$v) echo $k .' = '. $v.'<br>';
echo '</div>';
echo '<div style="float:left"><h3>SORTED</h3>';
foreach ($sorted as $k=>$v) echo $k .' = '. $v .'<br>';
echo '</div>';

PHP : Custom pagination in Wordpress

I use this code for my custom paging :
global $wpdb, $table_prefix, $current_user;
get_currentuserinfo();
$umail = $current_user->user_email;
$paged = $wpdb->get_results("SELECT * FROM {$table_prefix}comments WHERE comment_author_email = '$umail'");
$page = isset($_GET['page']) ? (int) $_GET['page'] : 1;
$pages = COUNT($paged);
$pages = ceil($pages / 2);
$querystring = "";
foreach ($_GET as $key => $value) {
if ($key != "page") $querystring .= "$key=$value&";
}
// Pagination
for ($i = 1; $i <= $pages; $i++) {
echo "<a " . ($i == $page ? "class=\"selected\" " : "");
echo "href=\"?{$querystring}page=$i";
echo "\">$i</a> ";
}
This code paginate my comments look like this : 1 2 3 4 5 6 7 8 9 10 11
How can change code to get paginate look like this: 1 2 3 ... 11
Thanks for any help.
Try the following loop:
$page = 8;//current page
$pages = 15;//count of all pages
$batch_middle = 5;//the approximate number of pages in the middle links to display. Current page will be in the middle
$batch_lr = 1;//number of pages in the left and right links
for($i = 1; $i <= $pages;$i++)
{
//display first links
if ($i <= $batch_lr)
{
echo $i . ' ';
continue;
}
//display last links
if ($i > $pages-$batch_lr)
{
echo $i . ' ';
continue;
}
//display middle links
if ($i>=($page-floor($batch_middle/2)) && $i<=($page+floor($batch_middle/2)))
{
echo $i . ' ';
continue;
}
//placeholder
echo ' ... ';
//move the pointer
$i = ($i < $page) ? ($page-floor($batch_middle/2)-1) : ($pages-$batch_lr) ;
}
//output example 1: 1 2 ... 14 15
//output example 2: 1 2 ... 7 8 9 ... 14 15
//output example 3: 1 2 3 4 5 ... 14 15
//output example 4: 1 ... 6 7 8 9 10 ... 15
Replace $page and $pages with your logic with getting a current page and count of total pages.
Replace the $batch_middle and $batch_lr to configure a number of links in the first, second and third batches of the links

Reversing page navigation on PHP

Can anyone help me with reversing this PHP page navigation?
Current script setting shows this format: [0] | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 ... 14 • Forward > • End >>>
But I really need it to reverse for this format: [14] | 13 | 12 | 11| 10 | 9 | 8 | 7 | 6 ... 0 • Back > • Start >>>
Here is the PHP code:
<?
$onpage = 10; // on page
function page(){
if(empty($_GET["page"])){
$page = 0;
} else {
if(!is_numeric($_GET["page"])) die("Bad page number!");
$page = $_GET["page"];
}
return $page;
}
function navigation($onpage, $page){
//----------------
$countt = 150;
$cnt=$countt; // total amount of entries
$rpp=$onpage; // total entries per page
$rad=4; // amount of links to show near current page (2 left + 2 right + current page = total 5)
$links=$rad*2+1;
$pages=ceil($cnt/$rpp);
if ($page>0) { echo "<<< Start <font color='#CCCCCC'>•</font> < Back <font color='#CCCCCC'>•</font>"; }
$start=$page-$rad;
if ($start>$pages-$links) { $start=$pages-$links; }
if ($start<0) { $start=0; }
$end=$start+$links;
if ($end>$pages) { $end=$pages; }
for ($i=$start; $i<$end; $i++) {
echo " ";
if ($i==$page) {
echo "[";
} else {
echo "<a href=\"?page=$i\">";
}
echo $i;
if ($i==$page) {
echo "]";
} else {
echo "</a>";
}
if ($i!=($end-1)) { echo " <font color='#CCCCCC'>|</font>"; }
}
if ($pages>$links&&$page<($pages-$rad-1)) { echo " ... ".($pages-1).""; }
if ($page<$pages-1) { echo " <font color='#CCCCCC'>•</font> Forward > <font color='#CCCCCC'>•</font> End >>>"; }
}
$page = page(); // detect page
$navigation = navigation($onpage, $page); // detect navigation
?>
for ($i=$end; $i>$start; $i--) {
echo " ";
if ($i==$page) {
echo "[";
} else {
echo "<a href=\"?page=$i\">";
}
//othercode
}
I found the solution for my question. Here is a link to reversed page navigation: php page navigation by serial number

Categories