Building html table using php - 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
⋅
⋅
⋅
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
Unpaired t-test in PHP
Is there a function, or example code, to do an unpaired t-test in PHP? I see there is a PHP function for a paired t-test (http://php.net/manual/en/function.stats-stat-paired-t.php) but I'm looking for the unpaired variety.
I found a PHP function (http://php.net/manual/en/function.stats-stat-independent-t.php) but its not documented and I'm not sure what value it is returning. So I created my own function, which returns more information. Hopefully this will be helpful to someone in the future: /* for calculating t-test's critical value */ $critval = array(0,6.3138,2.92,2.3534,2.1319,2.015,1.9432,1.8946,1.8595,1.8331,1.8124,1.7959,1.7823,1.7709,1.7613,1.753,1.7459,1.7396,1.7341,1.7291,1.7247,1.7207,1.7172,1.7139,1.7109,1.7081,1.7056,1.7033,1.7011,1.6991,1.6973,1.6955,1.6939,1.6924,1.6909,1.6896,1.6883,1.6871,1.6859,1.6849,1.6839,1.6829,1.682,1.6811,1.6802,1.6794,1.6787,1.6779,1.6772,1.6766,1.6759,1.6753,1.6747,1.6741,1.6736,1.673,1.6725,1.672,1.6715,1.6711,1.6706,1.6702,1.6698,1.6694,1.669,1.6686,1.6683,1.6679,1.6676,1.6673,1.6669,1.6666,1.6663,1.666,1.6657,1.6654,1.6652,1.6649,1.6646,1.6644,1.6641,1.6639,1.6636,1.6634,1.6632,1.663,1.6628,1.6626,1.6623,1.6622,1.662,1.6618,1.6616,1.6614,1.6612,1.661,1.6609,1.6607,1.6606,1.6604,1.6602,1.6601,1.6599,1.6598,1.6596,1.6595,1.6593,1.6592,1.6591,1.6589,1.6588,1.6587,1.6586,1.6585,1.6583,1.6582,1.6581,1.658,1.6579,1.6578,1.6577,1.6575,1.6574,1.6573,1.6572,1.6571,1.657,1.657,1.6568,1.6568,1.6567,1.6566,1.6565,1.6564,1.6563,1.6562,1.6561,1.6561,1.656,1.6559,1.6558,1.6557,1.6557,1.6556,1.6555,1.6554,1.6554,1.6553,1.6552,1.6551,1.6551,1.655,1.6549,1.6549,1.6548,1.6547,1.6547,1.6546,1.6546,1.6545,1.6544,1.6544,1.6543,1.6543,1.6542,1.6542,1.6541,1.654,1.654,1.6539,1.6539,1.6538,1.6537,1.6537,1.6537,1.6536,1.6536,1.6535,1.6535,1.6534,1.6534,1.6533,1.6533,1.6532,1.6532,1.6531,1.6531,1.6531,1.653,1.6529,1.6529,1.6529,1.6528,1.6528,1.6528,1.6527,1.6527,1.6526,1.6526,1.6525,1.6525); /* -------------------------------------------- */ /* ------- sd_square -------------------------- */ /* -------------------------------------------- */ // Function to calculate square of value - mean function sd_square($x, $mean) { return pow($x - $mean,2); } /* -------------------------------------------- */ /* ------- sd --------------------------------- */ /* -------------------------------------------- */ // Function to calculate standard deviation (uses sd_square) function sd($array) { // square root of sum of squares devided by N-1 return sqrt(array_sum(array_map("sd_square", $array, array_fill(0,count($array), (array_sum($array) / count($array)) ) ) ) / (count($array)-1) ); } /* -------------------------------------------- */ /* ------- unpairedttest ---------------------- */ /* -------------------------------------------- */ function unpairedttest($data1,$data2) { if ((count($data1) < 2) || (count($data2) < 2)) { return array(0,0,0,0,0); } /* compute stats about dataset1 */ $mean1 = array_sum($data1)/count($data1); $sd1 = sd($data1); $variance1 = $sd1*$sd1; $n1 = count($data1); $stderr1 = $variance1/$n1; /* compute stats about dataset2 */ $mean2 = array_sum($data2)/count($data2); $sd2 = sd($data2); $variance2 = $sd2*$sd2; $n2 = count($data2); $stderr2 = $variance2/$n2; $stderr = sqrt($stderr1 + $stderr2); $meandiff = abs($mean1-$mean2); if ($stderr > 0) { $tvalue = $meandiff/$stderr; } else { $tvalue = 0; } $df = $n1 + $n2 -2; if ($df > 100) { $criticaltvalue = $GLOBALS['critval'][100]; } else { $criticaltvalue = $GLOBALS['critval'][$df]; } if ($tvalue > $criticaltvalue) { /* they are statistical different */ $statisticallydifferent = 1; } else { /* they ain't */ $statisticallydifferent = 0; } return array($statisticallydifferent,$stderr,$meandiff,$tvalue,$df); }
Displaying Rows of HTML Elements in Vertical Rows
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>"; } ?>
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>';
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