PHP foreach with table rows - php

I have this PHP script here
$z = range(2, 123);
echo '<table width="100%">';
foreach($z as $x){
echo '<td><img src="http://www.mysite.net/' . $x . '/5.jpg" width=200></td>';
}
echo '</table>';
What I am trying to do is get 6 items in the table row and then a new row...how would I do this?
Thanks,
J

Here the modulo operator comes in. You can divide and calculate the remainder. Everytime the remainder is 0 you add a new row:
$z = range(2, 123);
echo '<table width="100%">';
echo '<tr>';
$cnt = 2;
foreach($z as $x){
if ( ($cnt - 2) % 6 == 0 ) {
echo '</tr><tr>';
}
$cnt++;
echo '<td><img src="http://www.mysite.net/' . $x . '/5.jpg" width=200></td>';
}
echo '</tr>';
echo '</table>';

If you want your codes nice and clean, always separate data manipulation from presentation code. Thus, move as much logic away from output, as possible.
So, first prepare your data
<?
$data = range(2, 123);
$data = array_chunk($data, 6);
?>
and then output it
<table width="100%">
<? foreach($data as $chunk): ?>
<tr>
<? foreach($chunk as $val): ?>
<td>
<img src="/<?=$val?>/5.jpg" width=200>
</td>
<? endforeach ?>
</tr>
<? endforeach ?>
</table>

Try something like this:
$z = range(2, 123);
echo '<table width="100%"><tr>';
foreach($z as $x){
if( ($x - 2) % 6 == 0 ) // Minus 2 because you don't start at 0 but at 2.
{
echo '</tr><tr>';
}
echo '<td><img src="http://www.mysite.net/' . $x . '/5.jpg" width=200></td>';
}
echo '</tr></table>';
The % is a Math function called modulo. More info can be found here.

Use a counter variable.
$z = range(2, 123);
$current_result=0;
echo '<table width="100%">';
echo '<tr>';
foreach($z as $x){
if ($current_result++ % 6 == 0) echo '</tr><tr>';
echo '<td><img src="http://www.mysite.net/' . $x . '/5.jpg" width=200></td>';
}
echo '</tr>';
echo '</table>';`

Well, for a start range(2, 123) is going to produce 122 numbers, so what you want is range(1, 6).
Then you need to fix your script to enclose each table cell in a row element, so your script becomes:
$z = range(1, 6);
echo '<table width="100%">';
foreach($z as $x){
echo '<tr><td><img src="http://www.mysite.net/' . $x . '/5.jpg" width=200></td></tr>';
}
echo '</table>';
Range is a bit of an oddball way of looping 6 times though - you might want to just use a string to build up the table and loop using while, then output the whole table in 1 go.
Edit
Seems I may have missed a point - if you are trying to loop 6 times within the range, then the modulo approach is what you want, although my point about the table row element is still needed otherwise you're not producing valid HTML.

just use any variable for count inside cycle. Increment it and check for you value.
For example
$cnt++;
if ($cnt >= 6) {
$cnt = 0;
echo "</tr><tr>";
}
And don't use foreach. Use for from 2 to 123

Related

How to print a dynamic table with 4 columns from PHP array and to add empty <td> to complete the table row

I have the following php array and I am trying to print a table with 4 columns. All is OK until the array has 4, 8, 12 and etc. keys /values but when array has length that can not be divided by 4 becomes the problem. Here is the sample array:
$newarray =array(
"make"=> "Ford" ,
"model"=> "S-MAX" ,
"model_year"=> "2009" ,
"made"=> "2010-01-01" ,
"manufacturer"=> "Ford Werke AG" ,
"manufacturer_address"=> "Koeln-Niehl, Germany" ,
"body"=> "Sedan/Saloon" ,
"engine_power_kw"=> "142" ,
"engine_displacement_ccm"=> "2000" ,
"engine_full"=> "2.0L Duratorq-TDCi (143PS) - DW"
);
and the code that prints the table:
$rama_result.='<table class="table w100 customtable">';
$i=1;
foreach($newarray as $key=>$value){
$rama_result1.= '<th>'.$key.'</th>';
$rama_result2.= '<td>'.$value.'</td>';
if($i % 4 == 0){
$rama_result.='</tr><tr>'.$rama_result1.'</tr><tr>'.$rama_result2.'</tr><tr>';
$rama_result1 = '';$rama_result2 = '';
}
$i++;
}
$rama_result.='</tr></table>';
Can you please help and show me the way to print the missing 2 in the last row so the code to work correct. Thank you for your help
The code above prints this table
<table class="table w100 customtable"><tbody>
<tr><th>make</th><th>model</th><th>model_year</th><th>made</th></tr>
<tr><td>Ford</td><td>S-MAX</td><td>2009</td><td>2010-01-01</td></tr><tr></tr>
<tr><th>manufacturer</th><th>manufacturer_address</th><th>body</th><th>engine_power_kw</th></tr>
<tr><td>Ford Werke AG</td><td>Koeln-Niehl, Germany</td><td>Sedan/Saloon</td> <td>142</td></tr>
<tr></tr></tbody></table>
<table class="table w100 customtable"><tbody>
<tr><th>make</th><th>model</th><th>model_year</th><th>made</th></tr>
<tr><td>Ford</td><td>S-MAX</td><td>2009</td><td>2010-01-01</td></tr><tr></tr>
<tr><th>manufacturer</th><th>manufacturer_address</th><th>body</th><th>engine_power_kw</th></tr>
<tr><td>Ford Werke AG</td><td>Koeln-Niehl, Germany</td><td>Sedan/Saloon</td> <td>142</td></tr>
<tr></tr></tbody></table>
Instead of looping each value use array_chunk to split the array then implode the headers and values.
$arr = array_chunk($newarray, 4, true);
echo "<table>\n";
foreach($arr as $sub){
echo "<tr><th>" . implode("</th><th>", array_keys($sub)) . implode("</th><th>", array_slice([" ", " ", " "],0 , 4-count($sub))) . "</th></tr>\n";
echo "<tr><td>" . implode("</td><td>", $sub) . implode("</td><td>", array_slice([" ", " ", " "],0 , 5-count($sub))) ."</td></tr>\n";
}
echo "</table>";
Output:
<table>
<tr><th>make</th><th>model</th><th>model_year</th><th>made</th></tr>
<tr><td>Ford</td><td>S-MAX</td><td>2009</td><td>2010-01-01 </td></tr>
<tr><th>manufacturer</th><th>manufacturer_address</th><th>body</th><th>engine_power_kw</th></tr>
<tr><td>Ford Werke AG</td><td>Koeln-Niehl, Germany</td><td>Sedan/Saloon</td><td>142 </td></tr>
<tr><th>engine_displacement_ccm</th><th>engine_full </th><th> </th></tr>
<tr><td>2000</td><td>2.0L Duratorq-TDCi (143PS) - DW </td><td> </td><td> </td></tr>
</table>
https://3v4l.org/TrCnM
Edited to include the empty cells.
You could just extend the array to have a multiple of 4 elements before you start:
for ($c = count($newarray); $c % 4 != 0; $c++) {
$newarray[str_repeat("\n", $c % 4)] = '';
}
$rama_result.='<table class="table w100 customtable">';
$i=1;
// ...
Demo on 3v4l.org
After the loop, you could check that there is something still in $rama_result1 - which would mean there is data left to be added into the table. This code pads the existing content with enough empty cells to make it up to the 4 columns (you can tweak the content if desired in the str_repeat() calls).
if ( $rama_result1 != '' ) {
$i--;
$rama_result1 .= str_repeat("<th />", 4-($i%4));
$rama_result2 .= str_repeat("<td />", 4-($i%4));
$rama_result.='<tr>'.$rama_result1.'</tr><tr>'.$rama_result2.'</tr>';
}
Also (as Nick pointed out) there are extra <tr> tags in various places. I've updated a few other parts of the code to try and tidy up the generated HTML...
$i=1;
foreach($newarray as $key=>$value){
$rama_result1.= '<th>'.$key.'</th>';
$rama_result2.= '<td>'.$value.'</td>';
if($i % 4 == 0){
$rama_result.='<tr>'.$rama_result1.'</tr><tr>'.$rama_result2.'</tr>'.PHP_EOL;
$rama_result1 = '';
$rama_result2 = '';
}
$i++;
}
if ( $rama_result1 != '' ) {
$i--;
echo ($i%4).PHP_EOL;
$rama_result1 .= str_repeat("<th />", 4-($i%4));
$rama_result2 .= str_repeat("<td />", 4-($i%4));
$rama_result.='<tr>'.$rama_result1.'</tr><tr>'.$rama_result2.'</tr>'.PHP_EOL;
}
$rama_result.='</table>';

how to create table with dynamic column using php

Suppose there is a number of item in array.which may be odd or even like I have an array which contain item from a to z Now I want to display that item in table . But As you know That There are 23 alphabets I want to display these alphabets in table which contains only 5 column in the last you got only three alphabets I want to display them in table . In the last I want that there should be three column not 5.
Here is my code i could not get that what should i do?
But the problem I faced in the below code is that the second loop is not correct.
<?php
$arr=array('a','b','c','d','e','f','g','h');
$count= sizeof($arr);
$row=ceil($count/5);
echo "<table border='1'>";
for($r=0;$r<$row;$r++){
echo "<tr>";
for($j=0;$j<=5;$j++){
echo "<td>'".$arr[$j]."'</td>";
}
echo "</tr>";
}
echo "</table>";
?>
My approach uses array_slice to take out pieces of the source and build rows:
$arr=array('a','b','c','d','e','f','g','h');
$offset = 0;
$num_columns = 5; //adjust number of columns
$table_html = "<table border='1'>";
while($slice = array_slice($arr,$offset,$num_columns)){
$offset += $num_columns;
$row_html = '';
foreach($slice as $n) $row_html .= "<td>$n</td>";
$table_html .= "<tr>$row_html</tr>";
}
$table_html .= '</table>';
echo $table_html;
Live demo
Try below code. Declaring number of column required in a variable, so which can be changed any time. closing the tr tag when loop count is same as number of columns to be displayed.
<?php
$arr=array('a','b','c','d','e','f','g','h');
$columnLength = 5;
echo "<table border='1'>";
echo "<tr>";
for($r=0;$r<count($arr) ; $r++){
echo "<td>'".$arr[$r]."'</td>";
if($r + 1 == $columnLength ) {
echo "</tr>";
}
}
echo "</table>";
?>

Printing output in Table with alternate row colors in PHP

So my code is below.The for loop is concatenating the elements from 2 arrays and printing them in a table.
I have 2 questions:
1) Although the output is correct I would like to print the output by calling the first function (fullname) in the second function (printTable).
2) I would like to print the output that is in the table rows in alternate colors of red and green.
<?php
$firstname=
array("Raj","Swati","Kunal","Hema","Kareena","Deepika","Shilpa","Amitabh","Shahrukh","Kangana");
$lastname=
array("Kumar","Sharma","Kapoor","Malini","Kapoor","Padukone","Shetty","Amitabh","Shahrukh","Kangana");
function fullname($fname,$lname){
for ($i=0; $i <10; $i++) {
$wholename[]=$fname[$i]." ".$lname[$i];
}
return $wholename;
}
function printTable($firstname,$lastname){
echo"<table border='1'>";
for($i=0;$i<10;$i++){
echo"<tr><td>".$firstname[i]." ".$lastname[i]."</td></tr>";
}
echo "</table>";
}
printTable($firstname,$lastname);
?>
Something like this:
<?php
$firstname=
array("Raj","Swati","Kunal","Hema","Kareena","Deepika","Shilpa","Amitabh","Shahrukh","Kangana");
$lastname=
array("Kumar","Sharma","Kapoor","Malini","Kapoor","Padukone","Shetty","Amitabh","Shahrukh","Kangana");
function fullname($index){
return $firstname[$index] . " " . $lastname[$index];
}
function printTable(){
echo"<table border='1'>";
for($i=0;$i<10;$i++){
echo"<tr><td>".fullname($i)."</td></tr>";
}
echo "</table>";
}
printTable();
?>
For the row colouring see: http://www.w3.org/Style/Examples/007/evenodd
If you don't want to use CSS for alternating row colours, you can use the remainder/mod operator % on the loop variable. $i % 2 means the remainder when $i is divided by 2 (ie, alternating 0,1,0,1,... as $i is incremented).
if (($i % 2) == 0) {echo "<tr bgcolor=#ff0000>"} else {echo "<tr bgcolor=#00ff00>"}

creating a table from 1 to 100 in php nested in html

This is a practice question I am having a problem with. So far, what I got to create is a table using the following code. I need help to fix it, with explanation on what my mistakes are.
What I am trying to to do is pretty simple: generating numbers from 1 to 100 in a table using php nested in an html code
Each 10 numbers should be in an aligned row, then break after 10
| 1 | 2 | . . . | 10 |
|11 | 12| .... | 20 |
|21 | 22| .... | 30 |
.
.
.
|91| 92 | ... |100|
<table border="1">
<?php
for ($x=1; $x <= 100; $x++){
if($x%11 ==0) {
echo "<tr><td>" . "<br>" . "</tr></td>";
}
echo "<tc><td>" . $x . "</td></tc>" ;
}
?>
</table>
Also using a for statement for the loop with if statement nested in it for the break the row
Could someone point out my mistakes in this code please.
all right the correct code should be like this:
<table border="1">
<?php
for ($x=1; $x <= 100; $x++){
if($x%10 ==1) {
echo "<tr>";
}
echo "<td>" . $x . "</td>" ;
}
?>
</table>
Thank you all for the help
We need to first understand the requirement.
Requirement:
Need incremental counter horizontally.
Every row should contain a whole 10 numbers starting from say 1 to 10, 11 to 20 etc.
So, if we consider the output as HTML table, <tr> increments by 11 and <td> increments by 1.
So, we need two loops: once incrementing by 10: the outer loop and other incrementing by 1: the inner loop.
So, write outer loop and inside it, add inner loop, both have step: 1
So, outer loop will increment the counter and inside it, inner loop will also run.
For every outer loop, the inner loop will run 10 times.
Thus, we get exact rows: 1-10, 11-20
Try this:
<table>
<?php
$k=0;
for ($i=0; $i<10; $i++) {
?>
<tr>
<?php
for ($j=0; $j<10; $j++) {
++$k;
?>
<td><?php print $k;?></td>
<?php
}
?>
</tr>
<?php
}
?>
</table>
Try this:
<?php
echo "<table border =\"1\" style='border-collapse: collapse'>";
for ($row=1; $row <= 10; $row++) {
echo "<tr> \n";
for ($col=1; $col <= 10; $col++) {
$p = $col * $row;
echo "<td>$p</td> \n";
}
echo "</tr>";
}
echo "</table>";
?>
<table>
<?php
for ($x=1; $x <= 100; $x++)
{
if($x%10 ==1)
**{
echo "<tr><td>" . "<br>" . "</tr></td>";**
}
echo "<tc><td>" . $x . "</td></tc>" ;
}
?>
</table>

Print one table, two-column PHP associative array as three side-by-side, two-column tables

I use the following to print a 15-row, two-column table from an associative arrray in PHP:
<table id="freq-table" class="table-list" cellspacing="0" cellpadding="10">
<tbody>
<?
$rowCount = 0;
foreach($word_frequency as $word => $frequency) if ($rowCount++ < 15) {?>
<tr>
<td><? echo $word; ?></td>
<td<? echo $frequency; ?></td>
</tr>
<?}?>
</tbody>
</table>
It works fine but takes up too much vertical space on the page. How can I format this into three side-by-side tables of five rows and two columns each with the first group having array items 1-5, the second group 6-10, and the last group 11-15? (refer to following illustration):
key1 value1 | key6 value6 | key11 value11
key2 value2 | key7 value7 | key12 value12
...
...
key5 value5 | key10 value10 | key15 value15
I've tried various table, div, container, and multiple loop experiments with very mixed (and unsuitable) results. Thank you in advance.
Since you can also use multiple columns to achieve this visual effect, you're going to probably want to format the data ahead of time to make the code of generating the table a little cleaner.
<?php
// Format the array data so each row contains all of the columns needed
$rows = array();
$max_per_column = 5;
$max_words = 15;
$rows = array_pad($rows, $max_per_column, array());
$count = 0;
foreach ($word_frequency as $word => $frequency) {
if ($count >= $max_words) {
break;
}
array_push($rows[$count % $max_per_column], $word, $frequency);
$count++;
}
?>
<table id="freq-table" class="table-list" cellspacing="0" cellpadding="10">
<tbody>
<?php
foreach ($rows as $cols) {
echo '<tr><td>' . implode('</td><td>', $cols) . '</td></tr>';
}
?>
</tbody>
</table>
Try some thing like that.
<table width="100%">
<tr>
<?php
$rowCount = 0;
foreach($word_frequency as $word => $frequency) if ($rowCount < 15) { ?>
<?php if($rowCount % 5 == 0) { ?>
<td><table border=1>
<?php } ?>
<tr>
<td><?php echo $word; ?></td>
<td><?php echo $frequency; ?></td>
</tr>
<?php if($rowCount % 5 == 4) { ?>
</table></td>
<?php } ?>
<?php $rowCount++; } ?>
</tr>
</table>
The only way to do this is to use a numeric key. For example
$word_frequency[0] = array();
$word_frequency[0]['word'] = "some word";
$word_frequency[0]['frequency'] = 10;
...
$word_frequency[15] = array();
$word_frequency[15]['word'] = "some other word";
$word_frequency[15]['frequency'] = 14;
Once you have your array, you could repeat the loop as follows
<table id="freq-table" class="table-list" cellspacing="0" cellpadding="10">
<tbody>
<?
$rowCount = 0;
for($i = 0; $i <= 5; $i++) {
$word[0] = $word_frequency[$i]["word"];
$frequency[0] = $word_frequency[$i]["frequency"];
$word[1] = $word_frequency[$i + 5]["word"];
$frequency[1] = $word_frequency[$i + 5]["frequency"];
$word[2] = $word_frequency[$i + 10]["word"];
$frequency[2] = $word_frequency[$i + 10]["frequency"];
?>
<tr>
<?
for($x = 0; $x <= 2; $x++ ){
?>
<td><? echo $word[$x]; ?></td>
<td<? echo $frequency[$x]; ?></td>
<?
}
?>
</tr>
<?
}
?>
</tbody>
</table>
Every $i loop creates the row, while the $x loop creates the columns. This assumes, of course, that you have at least 15 items, that you're going to create only 5 rows and three columns of key/value pairs.
Well, if I were doing it, I'd probably use a ul with a css columns :D
http://davidwalsh.name/css-columns
However, that's not a very "programmerly" thing to do.
It might help that you don't have to go through the array in order.
If you look at what you have, there is a pattern to the indices:
i + 0x, i + 1x, i + 2x, ...
Where x is your number of items divided by the number of columns.
and you stop iterating when i = total / x
Sorry to be too tired to code this for you but the gist is this:
$myarray = [1 ... 15];
$columns = 3;
$arrayKeys = array_keys($myarray);
$total = count($array);
$x = floor $total / $column;
for ($i = 0; $i > $x; $i += $x + 1 ){
echo $arrayKeys[$i] . " - " . $myarray($arrayKeys[$i]);
echo $arrayKeys[$i + $x] . " - " . $myarray($arrayKeys[$i + $x]);
echo $arrayKeys[$i + ($x * 2) ] . " - " . $myarray($arrayKeys[$i + ($x * 2)]);
}
Or something like that... that's off the top of my head and I think it has some issues, but you should be able to beat that into something that works.

Categories