Implement a multiple column table using foreach loop - php

I want to implement a logic for creating a three column table using foreach loop. A sample code will look like this.
$array = ['0','1','2','3','4','5','6'];
$table = '<table class="table"><tbody>';
foreach($array as $a=>$v){
//if 0th or 3rd???????????wht should be here?
$table .= '<tr>';
$table .= '<td>$v</td>';
//if 2nd or 5th??????????and here too???
$table .= '</tr>';
}
$table = '</tbody></table>';
Any ideas?
Expected output is a simple 3X3 table with the values from the array

Use this you may looking for this
<?php
echo('<table><tr>');
$i = 0;
foreach( $array as $product )
{
$i++;
echo '<td>'.$product .'</td>';
if($i % 3==0)
{
echo '</tr><tr>';
}
}
echo'</tr></table>';
?>
Result Here:
<table>
<tr>
<td>data1</td>
<td>data2</td>
<td>data3</td>
</tr>
<tr>
<td>data4</td>
<td>data5</td>
<td>data6</td>
</tr>
</table>

This should work for you:
(See that I added a tr at the start and end before and after the foreach loop. Also I changed the quotes to double quotes and made sure you append the text everywhere.)
<?php
$array = ['0','1','2','3','4','5','6'];
$table = "<table class='table'><tbody><tr>";
//^^^^ See here the start of the first row
foreach($array as $a => $v) {
$table .= "<td>$v</td>";
//^ ^ double quotes for the variables
if(($a+1) % 3 == 0)
$table .= "</tr><tr>";
}
$table .= "</tr></tbody></table>";
//^ ^^^^^ end the row
//| append the text and don't overwrite it at the end
echo $table;
?>
output:
<table class='table'>
<tbody>
<tr>
<td>0</td>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
<td>5</td>
</tr>
<tr>
<td>6</td>
</tr>
</tbody>
</table>

Here is an easy solution with array_chunk():
<?php
$array = array('0','1','2','3','4','5','6');
$d = array_chunk($array, 3);
$table = "<table border='1' class='table'><tbody>";
foreach($d as $v)
$table .= "<tr><td>" . implode("</td><td>", $v) . "</td></tr>";
$table .= "</tbody></table>";
echo $table;
?>

Here is an easy solution with incrementing that works with a dynamically generated table like the one in Magento product view page to help display product attributes in two table columns preceded by attribute label -> practically we have 4 table columns together with attribute labels. This is useful for products with multiple attributes that take a long page to display.
<?php
$_helper = $this->helper('catalog/output');
$_product = $this->getProduct();
if($_additional = $this->getAdditionalData()): ?>
<h2><?php echo $this->__('Additional Information') ?></h2>
<table class="table table-bordered table-hover" id="product-attribute-specs-table">
<col width="25%" />
<col />
<tbody>
<?php $i = 1; ?>
<tr>
<?php foreach ($_additional as $_data): ?>
<?php $_attribute = $_product->getResource()->getAttribute($_data['code']);
if (!is_null($_product->getData($_attribute->getAttributeCode())) && ((string)$_attribute->getFrontend()->getValue($_product) != '')) { ?>
<th style="width: 20%;"><?php echo $this->htmlEscape($this->__($_data['label'])) ?></th>
<td class="data" style="width:20%;"><?php echo $_helper->productAttribute($_product, $_data['value'], $_data['code']) ?></td>
<?php $i++; if($i > 1 && ($i & 1) ) echo "</tr><tr>";?>
<?php } ?>
<?php endforeach; ?>
</tr>
</tbody>
</table>
<script type="text/javascript">decorateTable('product-attribute-specs-table')</script>

Related

Quantity of every product outputs like 123. How can i put this in a table row table data

I am having a problem to convert my $quantity_total which is as example (113) from 3 different products.
I want it to be in a table like below.
I have been trying to use chunk_split and explode but if i was able to succeed in that. I wouldn't be able to make it dynamic.
<table>
<tr>
<th>Quantity</th>
</tr>
<tr>
<td>1</td>
</tr>
<tr>
<td>1</td>
</tr>
<tr>
<td>3</td>
</tr>
</table>
$total=0;
$item_count=0;
$arr = array();
$quantity_all = '';
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
extract($row);
$arr[] = $row;
$_SESSION['cart-checkout'] = $arr;
$quantity=$_SESSION['cart'][$id]['quantity'];
$quantity_all .=$quantity;
$sub_total=$price*$quantity;
echo "<div class='cart-row'>";
echo "<div class='col-md-8'>";
echo "<div class='product-name m-b-10px'><h4>{$name}</h4></div>";
echo $quantity>1 ? "<div>{$quantity} items</div>" : "<div>{$quantity} item</div>";
echo "</div>";
echo "<div class='col-md-4'>";
echo "<h4>$" . number_format($price, 2, '.', ',') . "</h4>";
echo "</div>";
echo "</div>";
$item_count += $quantity;
$total+=$sub_total;
$_SESSION['total'] = $total;
$_SESSION['item-count'] = $item_count;
}
$_SESSION['quantity-all'] = $quantity_all;
Is this possible? And i need it to be dynamic. So if it were 10 different quantities. It would make 10 table rows.
I hope someone can help me, would really appreciate it a lot! It's the last thing to finish my e-commerce webshop.
As mentioned in my comment, I don't think this is good solution... but the function you're looking for is str_split. https://stackoverflow.com/a/9814389/296555
http://sandbox.onlinephpfunctions.com/code/0bbee53cafafc0d5e8954e07d0abc2c86c6c89a8
<?php
$rows = '156165165489465131';
echo '<table>';
echo '<tr><th>Quantity</th></tr>';
foreach (str_split($rows) as $row) {
echo "<tr><td>$row</td></tr>";
}
echo '</table>';
I dont know if this Is what you want, but you can try something like:
<table>
<tr>
<td>Quantity</td>
</tr>
<?php
$characters = str_split( (string) $quantity_total);
foreach($characters as $char){
echo "
<tr>
<td> $char </td>
</tr>
";
}
?>
</table>

Loop through multiple arrays and list the result dynamically

I'm struggeling with this one. How can list all devices, their model and supplier from my database? The data is stored comma-separated in the fields device, model and supplier.
<?php
while ($row = mysqli_fetch_array($result)) {
$device_explode = explode(',', $row['device']);
$model_explode = explode(',', $row['model']);
$supplier_explode = explode(',', $row['supplier']);
$device = array(array($device_explode[0]), //count function? How would I do that?
array($model_explode[0]),
array($supplier_explode[0])
);
echo "<table border='1'>
<tr>
<th>Møterom</th>
<th>Romnummer</th>
<th>Lokasjon</th>
<th>Antall sitteplasser</th>
<th>Tilgjengelig utstyr</th>
<th>Bilde av rommet</th>
<th>Endre</th>
<th>Slett</th>
</tr>
<tr>
<td>".$row['name']."</td>
<td>".$row['roomnbr']."</td>
<td>".$row['location']."</td>
<td>".$row['seats']."</td>
<td>".$device[0][0]."<br>".$device[1][0]."<br>".$device[2][0]."<br></td> //also count?
<td><img src='../img/uploads/".$row['img']."' width='150px' ></td>
<td><a href='?p=editconfroomv2&id=".$row['id']."'>Endre</a></td>
<td><a href='./index.php?p=deleteconfroomdb&id=".$row['id']."' class='delete'>Slett</a></td>
</tr>
</table>";
}
?>
It can be done this way (if I understand correct your table structure). I assume, that $device_explode, $model_explode and $supplier_explode have equal number of elements:
<?php
// Table Header
echo "<table border='1'>
<tr>
<th>Møterom</th>
<th>Romnummer</th>
<th>Lokasjon</th>
<th>Antall sitteplasser</th>
<th>Tilgjengelig utstyr</th>
<th>Bilde av rommet</th>
<th>Endre</th>
<th>Slett</th>
</tr>";
while ($row = mysqli_fetch_array($result)) {
$device_explode = explode(',', $row['device']);
$model_explode = explode(',', $row['model']);
$supplier_explode = explode(',', $row['supplier']);
// Table rows
$td = '';
$td .=
"<tr>
<td>".$row['name']."</td>
<td>".$row['roomnbr']."</td>
<td>".$row['location']."</td>
<td>".$row['seats']."</td>
<td>";
for ($i = 0; $i < count($device_explode); $i++) {
$td .=$device_explode[$i]." ".$model_explode[$i]." ".$supplier_explode[$i]."<br>";
}
$td .=
"</td>
<td><img src='../img/uploads/".$row['img']."' width='150px' ></td>
<td><a href='?p=editconfroomv2&id=".$row['id']."'>Endre</a></td>
<td><a href='./index.php?p=deleteconfroomdb&id=".$row['id']."' class='delete'>Slett</a></td>
</tr>";
echo $td;
}
echo "</table>";
?>
I would suggest looping trough the arrays in the markup and generating the output using the html templating syntax and alternative control structures.
Some things i have done[not related directly to the question]:
switched the array() syntax for the shorthand [can be done since version 5.4]
switched from using a single echo to utilizing the html templating syntax [by expluding non dynamic parts from php and echoing the dynamic parts in]
Switched from using the echo statement to using the shorthand
Switched to alternative control structures
PHP documentation for strings
<?php
while ($row = mysqli_fetch_array($result)) {
$device_explode = explode(',', $row['device']);
$model_explode = explode(',', $row['model']);
$supplier_explode = explode(',', $row['supplier']);
//I am assuming you want to loop trough all exploded fields related to each row
$devices = [
$device_explode,
$model_explode,
$supplier_explode
];
?>
<?php while(($row = mysqli_fetch_array($result))) : ?>
<table border='1'>
<tr>
<th>Møterom</th>
<th>Romnummer</th>
<th>Lokasjon</th>
<th>Antall sitteplasser</th>
<th>Tilgjengelig utstyr</th>
<th>Bilde av rommet</th>
<th>Endre</th>
<th>Slett</th>
</tr>
<tr>
<td><?= $row['name'] ?></td>
<td><?= $row['roomnbr'] ?></td>
<td><?= $row['location'] ?></td>
<td><?= $row['seats'] ?></td>
<td>
<?php foreach ($devices as $deviceSpecs) : //Here we loop trough the first dimension fo the array ?>
<?php foreach ($deviceSpecs as $deviceSpec): //Here we loop trough the second dimension ?>
<?= $deviceSpec ?><br>
<?php endforeach; ?>
<?php endforeach; ?>
</td>
<td><img src='../img/uploads/<?= $row['img'] ?>' width='150px' ></td>
<td><a href='?p=editconfroomv2&id=<?= $row['id'] ?>>Endre</a></td>
<td><a href='./index.php?p=deleteconfroomdb&id=<?= $row['id'] ?>' class='delete'>Slett</a></td>
</tr>
</table>
<?php endwhile; ?>

mysql query to display results in repeating columns

I am trying to build a comparison table using mysql query and php.
I would like the result to be displayed in a columns, like this:
<table border="1" cellspacing="0" cellpadding="0">
<tr>
<td width="151" scope="col">product</td>
<td width="89" scope="col">product1</td>
<td width="78" scope="col">product2</td>
<td width="77" scope="col">product3</td>
</tr>
<tr>
<td>type</td>
<td>type2</td>
<td>type3</td>
<td>type5</td>
</tr>
<tr>
<td>size</td>
<td>size2</td>
<td>size1</td>
<td>size4</td>
</tr>
<tr>
<td>price</td>
<td>4.99</td>
<td>3.99</td>
<td>3.59</td>
</tr>
</table>
but I can only get the table to show the results - not a row title too (i.e. I want the first column to show 'product', 'type', 'size', 'price'.
The code I have so far is
<?php
// query the database
$result = mysql_query($query_getproducts);
// cols we are interested in (from the SQL query)
$cols = array(
'product',
'type',
'size',
'price',
);
// initialize rotated result using cols
$rotated = array();
foreach($cols as $col) {
$rotated[$col] = array();
}
// fill rotated array
while(($row = mysql_fetch_assoc($result)) !== false) {
foreach($cols as $col) {
$rotated[$col][] = $row[$col];
}
}
// echo html
echo "<table border=1 width=473>";
echo "<tr>";
echo "</tr>";
foreach($rotated as $col => $values) {
echo "<tr>";
foreach($values as $value) {
echo "<td> " . htmlentities($value) . "</td>";
}
echo "</tr>";
}
echo "</table>";
?>
hope someone can help.
First of all mysql_* functions are deprecated. You should use PDO or Mysqli.
If you want table headers static ie you want to show table header as "Product,Type,Size, Price"
Then use
<tr>
<th>Product</th>
<th>Type</th>
<th>Size</th>
<th>Price</th>
</tr>
Then if your should use mysql_fetch_assoc which returns associative array with column name as there key. You can use that array and print the result using loop.
eg:
<?php
$rs=mysql_query($query);
while($row=mysql_fetch_assoc($rs) ){
?>
<tr>
<td><?php echo $row['keyname']?></td>
.....
.....
</tr>
<?php
}
?>
try like this ,
echo "<table border=1 width=473>";
echo " <tr>
<th>Product Name</th>
<th>Description</th>
<th>Product Size</th>
<th>Price</th>
</tr>";
foreach($rotated as $col => $values) {
echo "<tr>";
foreach($values as $value) {
echo "<td> " . htmlentities($value) . "</td>";
}
echo "</tr>";
}
echo "</table>";

create a new array based on a function

I'm just learing to use php, and I've been working on this code that is not very efficient because it is very long and I would like it to be more automated. The idea is to generate a table with 2 colums, one with the user name and the other with the score of each user. As you may imagine, the score is based on a function that use other variables of the same user. My goal is to only have to set one variable for each user and a new row is would be created automatically at the end of the table.
<?php
$array1['AAA'] = "aaa"; ## I'm suposed to only set the values for array1, the rest
$array1['BBB'] = "bbb"; ## should be automatic
$array1['ETC'] = "etc";
function getscore($array1){
## some code
return $score;
};
$score['AAA'] = getscore($array1['AAA']);
$score['BBB'] = getscore($array1['BBB']);
$score['ETC'] = getscore($array1['ETC']);
?>
<-- Here comes the HTML table --->
<html>
<body>
<table>
<thead>
<tr>
<th>User</th>
<th>Score</th>
</tr>
</thead>
<tbody>
<tr>
<td>AAA</td> <-- user name should be set automaticlly too -->
<td><?php echo $score['AAA'] ?></td>
</tr>
<tr>
<td>BBB</td>
<td><?php echo $score['BBB'] ?></td>
</tr>
<tr>
<td>ETC</td>
<td><?php echo $winrate['ETC'] ?></td>
</tr>
</tbody>
</table>
</body>
</html>
Any help would be welcome!
$outputHtml = ''
foreach( $array1 as $key => $val )
{
$outputHtml .= "<tr> ";
$outputHtml .= " <td>$key</td>";
$outputHtml .= " <td>".getscore($array1[$key]);."</td>";
$outputHtml .= " </tr>";
}
then in $outputHtml will be html content with all rows you wanna display
This is a little cleaner, using foreach and printf:
<?php
$array1 = array(
['AAA'] => "aaa",
['BBB'] => "bbb",
['ETC'] => "etc"
);
function getscore($foo) {
## some code
$score = rand(1,100); // for example
return $score;
};
foreach ($array1 as $key => $value) {
$score[$key] = getscore($array1[$key]);
}
$fmt='<tr>
<td>%s</td>
<td>%s</td>
</tr>';
?>
<-- Here comes the HTML table --->
<html>
<body>
<table><thead>
<tr>
<th>User</th>
<th>Score</th>
</tr></thead><tbody><?php
foreach ($array1 as $key => $value) {
printf($fmt, $key, $score[$key]);
}
?>
</tbody></table>
</body>
</html>
Also, I'll just note that you don't seem to be using the values of $array1 anywhere. Also,
I'm not sure what $winrate is in your code, so I ignored it.

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