Dynamically generate table using PHP - php

I know this has been asked before and I have got it working using the following code:
<?php
$maxcols = 8; $i = 0;
echo "<table id='table1'><tr>";
foreach ($id as $k => $v) {
echo "<td id='0'><div id='{$k}' class='drag t1'>{$v}</div></td>"; $i++;
if ($i == $maxcols) { $i = 0; echo "</tr><tr>"; }
} $i++;
while ($i <= $maxcols) {
$i++; echo "<td></td>";
}
echo "</tr></table>";
?>
This results in a table that looks like this :
I'd like to add headers to this so the end result looks like this:
I'd like to do it dynamically so if I create a table that is only 5 columns wide I'd get on the first header row ID01 - ID05 and on the second header row ID06 - ID10
I want to limit the header ID values to be no more than $maxid any extra header fields should be blank, like this : If $maxid = 12; then :
I need the header rows are made as follows and not using <TH>
<td class="mark">
I'm using some javascript to allow the movement of cell data.
The class is used to set the formatting on the header and stop items from being dragged into the fields.
Can anyone point me in the right direction on how to do this.

This should help you.
$maxcols = 8;
$maxid = 12;
$startid = 1;
echo "<table id='table1'>\n";
for ($i = 1;$i<=ceil($maxid/$maxcols);$i++) {
echo "<tr>\n";
for ($j=1;$j<=$maxcols;$j++)
if ($startid <= $maxid)
echo " <td class='mark'>ID".$startid++."</td>\n";
else
echo " <td> </td>\n";
echo "</tr>\n<tr>\n";
for ($j=1;$j<=$maxcols;$j++)
echo "<td>Content</td>\n";
echo "</tr>\n";
}
echo "</table>\n";
Generates
<table id='table1'>
<tr>
<td class='mark'>ID1</td>
<td class='mark'>ID2</td>
<td class='mark'>ID3</td>
<td class='mark'>ID4</td>
<td class='mark'>ID5</td>
<td class='mark'>ID6</td>
<td class='mark'>ID7</td>
<td class='mark'>ID8</td>
</tr>
<tr>
<td>Content</td>
<td>Content</td>
<td>Content</td>
<td>Content</td>
<td>Content</td>
<td>Content</td>
<td>Content</td>
<td>Content</td>
</tr>
<tr>
<td class='mark'>ID9</td>
<td class='mark'>ID10</td>
<td class='mark'>ID11</td>
<td class='mark'>ID12</td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>Content</td>
<td>Content</td>
<td>Content</td>
<td>Content</td>
<td>Content</td>
<td>Content</td>
<td>Content</td>
<td>Content</td>
</tr>
</table>

try this. It will work in the same way as you desired
<?php
$id= array("1","2","3","4","5","6","7","8","9","10","11","12");
$maxcols = 8; $i = 0;$j=0;$t=0;$s=0;
$maxid = count($id);
echo "<table id='table1'><tr>";
foreach ($id as $k => $v)
{
if($t == 0)
{
while ($t <= $maxcols-1) {
if($s < $maxid)
{
$s++;$t++; echo "<td class='mark'>id$s</td>";
}
else
{
echo "<td class='mark'></td>";$t++;$s++;
}
}
echo "</tr><tr>";
}
else
{
}
echo "<td id='0'><div id='{$k}' class='drag t1'>{$v}</div></td>"; $i++;
if ($i == $maxcols)
{
echo "</tr><tr>";
if($j == 0)
{
while ($j <= $maxcols-1) {
if($s < $maxid)
{
$s++;$j++; echo "<td class='mark'>id$s</td>";
}
else
{
echo "<td class='mark'></td>";$j++;$s++;
}
}
echo "</tr><tr>";
}
$i=0;
}
}
echo "</tr></table>";
?>
Output

Hi You can Use My Library:
class generate{
private $row = "<tr>{columns}</tr>";
private $td = "<td {attr}>{data}</td>";
private $attributeTR="";
private $attributeTD="";
private $tdBuilder="";
public function addCol($ColumValsArr=array("class='motota'"=>"Example")){
foreach($ColumValsArr as $key=>$val){
$newCol = str_replace("{data}",$val,$this->td);
$newCol = str_replace("{attr}",$key,$newCol);
$this->tdBuilder .= str_replace("{data}",$key,$newCol);
}
}
public function getRow(){
return str_replace("{columns}",$this->tdBuilder,$this->row);
}
}

<?php
function TableFunc($Data)
{
$Table = "<table>" . PHP_EOL;
foreach ($Data as $tags => $array) {
$Table .= "<$tags>" . PHP_EOL;
foreach ($array as $thead) {
$tag=$tags==="tbody"?"td":"th";
$Table .= "<tr>" . PHP_EOL;
if (is_array($thead)) {
foreach ($thead as $theadItem) {
if (is_array($theadItem))
$Table .= "<$tag colspan='$theadItem[1]'>$theadItem[0]</$tag>" . PHP_EOL;
else
$Table .= "<$tag>$theadItem</$tag>" . PHP_EOL;
}
}
$Table .= "</tr>" . PHP_EOL;
}
$Table .= "</$tags>" . PHP_EOL;
}
$Table .= "</table>" . PHP_EOL;
return $Table;
}
$Data = array(
"thead" => [
[["GENEL BİLGİ", 2], ["KALORİMETRE (ISINMA)", 2], ["HESAPLAMA", 2]],
["NO", "AD SOYAD", "FARK", "TUTAR", "OKUMA", "ÖDENECEK"]
],
"tbody"=>array(
array("1","MURAT DURAN","100","100.00","10.00","110.00"),
array("1","MURAT DURAN","100","100.00","10.00","110.00"),
array("1","MURAT DURAN","100","100.00","10.00","110.00"),
array("1","MURAT DURAN","100","100.00","10.00","110.00"),
),
"tfoot" => [["NO", "AD SOYAD", "M2", "MAHSUP", "SAYAÇ", "15°", "FARK", "TUTAR", "ORTAK ALAN", "EKSTRA", "MUAFİYET", "OKUMA", "ÖDENECEK"]]
);
echo TableFunc($Data);

Related

Unable to show row and columns dynamically using rowspan in php

I'm trying to show booking using tables, which have dynamic rows and also rowspan.
Here is my code:
<table border="1" style='width: 100%' >
<tr>
<th style='background-color:green;width: 80px' ><font color="white">Time</font></th>
<?php
$i=1;
while($i<=$no_court)
{
echo "<th style='background-color:green;width: 80px'> <font color='white'>Court".$i."</font></th>";
$i+=1;
}
?>
</tr>
<tr>
<td>8:00 AM</td>
<?php
$i=1;
while($i<=$no_court)
{
$flag=0;
$j=0;
while(sizeof($start) > $j )
{
$start_time=$start[$j];
$finish_time=$finish[$j];
$court=$court1[$j];
$sst = strtotime($start_time);
$eet= strtotime($finish_time);
$diff= $eet-$sst;
$timeElapsed= gmdate("h:i",$diff);
$timeElapsed+=1;
if ($start_time=='08:00:00' && $court==$i)
{
$fio_time=$finish[$j];
if($fio_time=='13:00:00')
{
$f_time='1:00:00';
}
$f=$facility_id[$j];
$sql15 = $dbConnection->prepare('SELECT * FROM tbl_facility WHERE facility_id=?');
$sql15->execute(array($f));
$row15 = $sql15->fetch();
$facility_name=$row15['facility_name'];
if($block_by[$j]=="1")
{
echo "<td style='background-color:blue;' rowspan='$timeElapsed'>
<font size='2' color='white'><b><center>$league[$j]</b></br>
Reserved </br>
$facility_name</br>
$start_time-$f_time</br>
<a href='' onClick='javascript: openPopup($id[$j])' style='color:white;'>Edit</a>
<a href='delete.php?id=$id[$j]' style='color:white;' onclick='return confirmdelete()' >Delete</a>
</center></font></td>";
break;
}
elseif($block_by[$j]=="2")
{
$p=$player_id[$j];
$sql17 = $dbConnection->prepare('SELECT * FROM tbl_player_registration WHERE player_id=?');
$sql17->execute(array($p));
$row17 = $sql17->fetch();
$first_name=$row17['first_name'];
echo "<td style='background-color:gray;' rowspan='$timeElapsed'>
<font size='2' color='white'><b><center>Reserved By</b></br>
$first_name </br>
</center></font></td>";
break;
}
}
elseif($start_time <='08:00:00' && $finish_time >='08:00:00' && $court==$i )
{
break;
}
elseif($court==$i )
{
$l=0;
while(sizeof($court) > $l)
{
$ta=$start[$l];
$fa=$finish[$l];
$ca=$court1[$l];
if($ta >='08:00:00' && $fa <='08:00:00' && $ca==$i )
{
$flag=1;$court=$ca;
}
$l+=1;
}
}
$j+=1;
}
if($flag==1 )
{
echo "<td></td>";
}
if($flag==0 )
{
}
if($court != $i)
{
echo "<td></td>";
}
$i+=1;
}
?>
</tr>
</table>
Its showing output as this image:
Its showing data properly but adding an extra column, which make the table look disturbing.
I want to show the result as this image:
I'm little confused where I'm messing the code. Kindly help to sort this issue.

php foreach create html table autometic generate tr tag?

hello friends i want to display two td tag in one tr.
this is is write into foreach loop.
this is my code.
$rri=0;
foreach ($related as $key => $value) {
if($rri % 2 == 0 ){
echo "<tr class='dsfdsf'>";
echo "<td >".$rri."</td>";
echo "</tr>";
}else{
echo "<td >".$rri."</td>";
}
$rri++;
}
this is my php code it return out put is under
<table>
<tr class='dsfdsf'>
<td>1</td>
</tr>
<tr>
<td>2</td>
</tr>
<tr class='dsfdsf'>
<td>3</td>
</tr>
<tr>
<td>4</td>
</tr>
<tr class='dsfdsf'>
<td>5</td>
</tr>
</table>
i want to output like this
<table>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td>5</td>
</tr>
</table>
foreachloop add new tr tag.
i checked odd or even this is working but unfortunate tr is added.
please help,
Thank you.
Hope this will help find your solution in a different but effective way:
<?php
$related = array(1,2,3,4,5);
$chunk = 2;
?>
<table>
<?php foreach (array_chunk($related, $chunk) as $row): ?>
<tr>
<?php foreach ($row as $val): ?>
<td><?php echo $val; ?></td>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
</table>
Put the </tr> oudside the if and set it in else statement.
echo '<table>';
$rri=0;
foreach ($related as $key => $value) {
if($rri % 2 == 0 ){
echo '<tr class="dsfdsf">';
echo '<td>'.$rri.'</td>';
}else{
echo '<td>'.$rri.'</td>';
echo '</tr>';
}
$rri++;
}
echo'</table>';
This should work
$rri=0;
foreach ($related as $key => $value) {
if($rri % 2 == 0 ){
if($rri > 0){
echo "</tr>";
}
echo "<tr class='dsfdsf'>";
}
echo "<td>".$rri."</td>";
$rri++;
}
you can try this
$rri=1;
echo "<tr class='dsfdsf'>";
foreach ($related as $key => $value) {
echo "<td >".$rri."</td>";
if($rri % 2 == 0 ){
echo "</tr><tr>";
}
$rri++;
}
echo "</tr>";
<?php
$related=array('1','2','3','4');
$rri=0;
echo "<table border=1 width=500>";
foreach ($related as $key => $value) {
if($rri % 2 == 0 || $rri==0 ){
echo "<tr class='dsfdsf'>";
}
echo "<td >".$rri."</td>";
if($rri/2 == 0 && $rri!=0 ){
echo "</tr>" ;
}
$rri++;
} echo "</table>";?>
Try This
for ($i = 0; $i <= $rri; $i+=2) {
echo "<tr class='dsfdsf'>\n";
echo "<td>$i</td>\n";
echo "<td>$i+1</td?\n";
echo "</tr>\n";
}

Position on foreach

How to start the position into 1 instead of 0?
Because the first name starts in 0. All I need to do is to make the first name to start in 1 and end in 50.
Is there any way to solve this problem?
here are my code:
<html>
<head>
<title>SEATPLAN</title>
</head>
<body>
<table border = "2" cellpadding = "20" cellspacing = "10">
<tr>
<td colspan = 5 rowspan = 2> </td>
<td align = "center"> Teachers Table</td>
<td colspan = 5 rowspan = 2> </td>
</tr>
<tr>
<td colspan = 1 rowspan = 6 width="1000"> </td>
</tr>
<?php
$names = array('Acog','Alaya-ay','Anino','Balsa','Baron','Borda','Bravo','Dalagan','Detumal','Enriquez',
'Hernane','Jose','Laminero','Montilla','Moraclo','Ogang','Palencia','Palencia','Pandili',
'Ramo','Ravelo','Septio','Tapel','Tayone','Trinidad','Yntong','Student','Student','Student',
'Student','Student','Student','Student','Student','Student','Student','Student','Student',
'Student','Student','Student','Student','Student','Student','Student','Student','Student'
,'Student','Student','Student');
?>
<?php
foreach($names as $position => $name){
echo "<td width='500' align='center'>".$position."<br>".$name."<br/>";
if ($position == 9){
echo "<tr width='500' align='center'>"."<br/>";}
if ($position == 19){
echo "<tr width='500' align='center'>"."<br/>";}
if ($position == 29){
echo "<tr width='500' align='center'>"."<br/>";}
if ($position == 39){
echo "<tr width='500' align='center'>"."<br/>";}
}
?>
</table>
</body>
</html>
This is the simplest solution if you later want to use the key ($position) for anything else:
echo "<td width='500' align='center'>".($position+1)."<br>".$name."<br/>";
I'd use:
$i = 1;
foreach($names as $name) {
echo '<td>'. $i .': '. $name .'</td>';
if($i % 10 == 0)
echo '</tr><tr>';
$i++;
}
Just add a new variable and initialize it with $position + 1.
foreach($names as $position => $name){
$newPosition = $position + 1;
echo "<td width='500' align='center'>".$newPosition."<br>".$name."<br/>";
.
.
}
This will preserve the value of current $position also.
All numeric arrays start with 0 as it's first index.
Just do this trick, it won't change the array structure but will show what you want:
foreach($names as $position => $name){
echo "<td width='500' align='center'>".($position+1)."<br>".$name."<br/>";
// rest of the code
}
So it will always add 1 to the actual position.

Creating a table that multiplies height by weight

How would I create a table that multiples height by weight?
I have no idea how to figure it out!
I am trying to create a BMI calculator.
// collect values from a form sent with method=get
$min_weight = mysql_real_escape_string($_GET["min_weight"]);
$max_weight = mysql_real_escape_string($_GET["max_weight"]);
$min_height = mysql_real_escape_string($_GET["min_height"]);
$max_height = mysql_real_escape_string($_GET["max_height"]);
?>
<table>
<tr>
<td>Key:</td>
<td class="good show">Healthy (20-25)</td>
<td cla ss="warning show">Overweight (25-30)</td>
<td class="bad show">Unhealthy ( -20 or 30+)</td>
</tr>
</table>
<table border="1">
<?php
echo "<tr><td>Height →<br>Weight ↓</td>";
for ( $i = $min_height; $i <= $max_height; $i+=5 )
{
echo "<td>{$i}</td>";
}
echo "</tr>";
for ( $j = $min_weight; $j <= $max_weight; $j+=5 )
{
echo "<tr>";
echo "<td>{$j}</td>";
echo "</tr>";
}
This should do the job, i've also put some isset()'s:
<?php
// collect values from a form sent with method=get
$min_weight = isset($_GET["min_weight"]) ? mysql_real_escape_string($_GET["min_weight"]):0;
$max_weight = isset($_GET["max_weight"]) ? mysql_real_escape_string($_GET["max_weight"]):0;
$min_height = isset($_GET["min_height"]) ? mysql_real_escape_string($_GET["min_height"]):0;
$max_height = isset($_GET["max_height"]) ? mysql_real_escape_string($_GET["max_height"]):0;
?>
<table>
<tr>
<td>Key:</td>
<td class="good show">Healthy (20-25)</td>
<td class="warning show">Overweight (25-30)</td>
<td class="bad show">Unhealthy ( -20 or 30+)</td>
</tr>
</table>
<?php
$table = '<table border="1">';
$table .= '<tr><td>Height →<br>Weight ↓</td>';
for ($i = $min_height;$i <= $max_height;$i += 5){
$table .= "<td>$i</td>";
}
$table .= "</tr>";
for($j = $min_weight; $j <= $max_weight;$j += 5){
$table .= "<tr><td>$j</td>";
for ($i = $min_height;$i <= $max_height;$i += 5){
$table .= '<td>'. $i * $j .'</td>';
}
$table .= '</tr>';
}
$table .= '</table>';
echo $table;
?>
Even though this works is it wrong to have the table border outside of the php tags?
<table>
<tr>
<td>Key:</td>
<td class="good show">Healthy (20-25)</td>
<td class="warning show">Overweight (25-30)</td>
<td class="bad show">Unhealthy ( -20 or 30+)</td>
</tr>
</table>
<table border="1">
<?php
echo "<tr><td>Height →<br>Weight ↓</td>";
for ( $j = $min_height; $j <= $max_height; $j+=5 )
{
echo "<td>{$j}</td>";
}
for ( $i = $min_weight; $i <= $max_weight; $i+=5 )
{
echo "<tr><td>{$i}</td>";
for ( $j = $min_height; $j <= $max_height; $j+=5 )
{
$var = number_format(($i)/(($j/100)*($j/100)),'2','.','');
{
echo "<td class='warning'>";
}
echo $var;
echo "</td>";
}
echo "</tr>";
}
?>
</table>

PHP AND FOR LOOP

I am trying to use for loops to create a table which dynamically returns something like this: Note how the td content have been arranged
<table>
<tr>
<td>1</td>
<td>3</td>
<td>5</td>
<td>7</td>
<td>9</td>
</tr>
<tr>
<td>2</td>
<td>4</td>
<td>6</td>
<td>8</td>
<td>10</td>
</tr>
</table>
among What I have tried so far is
$row=2;
$col=20;
$x=0;
echo '<table>';
for($i=0;$i<$row;$i++){
echo '<tr>';
for($k=0;$k<$col;$k++)
{
echo '<td>'.echo $x+=1.'</td>';
}
echo '</tr>';
}
In this case I get something different and which is not what I want.
<table>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
</tr>
<tr>
<td>6</td>
<td>7</td>
<td>8</td>
<td>9</td>
<td>10</td>
</tr>
</table>
Kindly someone help me map this.Thanks
<?php
# how high to count
$count = 10;
# how many rows in the table
$rows = 2;
# figure out how many columns
$columns = ceil($count/$rows);
# could also go the other way and declare there to be 5 columns and then
# divide to get the rows, but since you're counting down the columns,
# I thought this made more sense. Either way.
?><table><?php
for ($i=0; $i<$rows; ++$i) {
?><tr><?php
for ($j=0; $j<$columns; ++$j) {
# calculate which number to show in column $j of row $i. Each column adds
# $rows numbers to the total, while each row just adds one more. And we
# want to start at 1 instead of 0.
$n = $j * $rows + $i + 1;
?><td><?= $n ?></td><?php
}
?></tr><?php
}
?></table>
$total_count = 10;
$total_rows = 2;
$table = array();
//building table array
for($i=1;$i<=$total_count;$i++) {
$row = $i % $total_rows;
$row = $row == 0 ? $total_rows : $row;
$table[$row][] = $i;
}
//generate table based on array
echo "<table>";
for($row=1;$row<=$total_rows;$row++) {
echo "<tr>";
foreach($table[$row] as $cell) {
echo "<td>".$cell."</td>";
}
echo "</tr>";
}
echo "</table>";
This isnt as complicated as people are making it seem
Start the inner loop at whatever row you're currently on and add 2 each time.
<?php
$rows=2;
$cols=10;
?>
<table>
<?php for($i=1;$i<=$rows;$i++): ?>
<tr>
<?php for($k=$i;$k<$cols;$k+=2): ?>
<td><?php echo $k ?></td>
<?php endfor; ?>
</tr>
<?php endfor; ?>
</table>
Id probably use range and foreach though
<?php
$rows=2;
$cols=10;
?>
<table>
<?php foreach( range( 1, $rows ) as $row ): ?>
<tr>
<?php foreach( range( $row, $cols, 2 ) as $col ): ?>
<td><?php echo $col ?></td>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
</table>
This approach will split the data itself
function array_chunk_vertical($array = null,$cols = 3, $pad = array(null))
{
if (is_array($array) == true and !empty($array))
{
$rows = ceil(count($array)/$cols);
$array = array_chunk($array,$rows);
if (count($array) < $cols)
{
$array = array_pad($array,$cols,$pad);
}
foreach($array as $key => $value)
{
$array[$key] = array_pad($value,$rows,null);
}
foreach($array as $key => $value)
{
foreach($value as $sub_key => $sub_value)
{
$output[$sub_key][$key] = $sub_value;
}
}
return $output;
}
return $array;
}
$data = array(1,2,3,4,5,6,7,8,9,10,11);
echo '<table border="1">';
foreach(array_chunk_vertical($data,ceil(count($data)/2)) as $row)
{
echo '<tr>';
foreach($row as $col)
{
echo '<td>' . $col . '</td>';
}
echo '</tr>';
}
echo '</table>';

Categories