$value
"...">

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


You can keep track of for example a module if you should start a new line or not.



+1


a source


EDITED after reformatting the question

I think you just need something in the line:



echo '<table><tr>';
$n = 0;

foreach ($a as $key => $value) 
        {
        if ($n==3)
             {
             $n = 0;
             echo '</tr><tr>';
             }

        echo '<td>'.$value.'</td>';
        $n++;
        }
 echo '</tr></table>';

      

+1


a source


You can do this:

$counter = 0;
foreach ($a as $key => $value) {
   $counter++;

   if (($counter % 3) === 0)
   {
     echo "<DIV id='container'>
      <DIV id='middle'>$value</DIV>
      </DIV>";
   }
   else
   {
     echo "<DIV id='container' style='float:left;'>
      <DIV id='middle'>$value</DIV>
      </DIV>";
   }
}

      

+1


a source


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


Just use this,

foreach ($a as $key => $value) {
     echo "<DIV id='container' style='display:inline'>
     <DIV id='middle' style='display:inline'>$value</DIV>
     </DIV>";
     //echo "<br />$key:$value<br />\n";
  }

      

add a break statement depending on your second line.

0


a source


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







All Articles