Display php foreach values in div
I have
foreach ($a as $key => $value) {
echo "<DIV id='container'>
<DIV id='middle'>$value</DIV>
</DIV>";
//echo "<br />$key:$value<br />\n";
}
which displays the result one below the other like
1234 5678 2010-05-20 5678 1590 2010-05-19
but i want it in a table like structure like
1234 5678 2010-05-20
5678 1590 2010-05-19
How can i do this?
+2
a source to share
6 answers
Kind of what nico said:
foreach ($a as $key => $value)
{
echo '<div style="width:33%;float:left">'.$value.'</div>';
}
Or what the don said:
$i = 0;
$open = false;
echo '<table>';
foreach( $a as $key => $value )
{
if( 0 == $i % 3 ) {
echo '<tr>';
$open = true;
}
echo "<td>$value</td>";
if( 2 == $i % 3 ) {
echo '</tr>';
$open = false;
}
$i++;
}
if( $open )
echo '</tr>';
echo '</table>';
+1
a source to share
By default, divs don't float next to each other. You can give all divs except every third one float: left
in style. It is good to use a table, however, if you are displaying a table.
If you can get the value $key
to start a new line or not, you can do something like:
echo '<table><tr>';
foreach ($a as $key => $value) {
if($key == 'somevalue'){
//start a new row if the $key allow
echo '</tr><tr>';
}
echo '<td>'.$value.'</td>';
}
echo '</tr></table>';
If you cannot get $key
wether to start a new line or not, use a counter, for example:
echo '<table><tr>';
$cnt = 0;
foreach ($a as $key => $value) {
if($cnt % 3 == 0){
//start a new row if this row contians 3 cells
echo '</tr><tr>';
}
echo '<td>'.$value.'</td>';
$cnt++;
}
echo '</tr></table>';
0
a source to share