Welcome Guest, Not a member yet? Register   Sign In
Making tables
#1

[eluser]Kemik[/eluser]
Hey,

Say I have a list of 20 items (number is dynamic). How would I get it so that they are split in to three columns?

E.g.

1 2 3
4 5 6
7 8 9
...

Thanks
#2

[eluser]gtech[/eluser]
sure there is a nicer way but this view works

Code:
<?php
  $counter=0;
  $cols=3;
  $list = array('0','2','1','2','9','0','1','2','9','2','1','2','9','0');
?>
<table border=1>
  &lt;?php foreach($list as $val):?&gt;
    &lt;?php if($counter==$cols) {$counter=0;}?&gt;
    &lt;?php if($counter==0):?&gt;<tr>&lt;?php endif;?&gt;
    <td>&lt;?=$val?&gt;</td>
    &lt;?php if($counter==($cols-1)):?&gt;
      </tr>
    &lt;?php endif;?&gt;
    &lt;?php $counter ++;?&gt;
  &lt;?php endforeach?&gt;

  &lt;?php for ( $i = 0; $i <= (($cols-1)-$counter); $i ++):?&gt;
    <td>-</td>
  &lt;?php endfor?&gt;
  &lt;?php if($counter!=$cols):?&gt;
     </tr>
  &lt;?php endif;?&gt;
</table>
#3

[eluser]Pascal Kriete[/eluser]
Here's a little helper based on gtech's code.
Code:
function make_table($arr, $cols = 3)
{
    $rem = count($arr) % $cols;
    $out = '';
    
    if($rem != 0)
    {
        $arr = array_pad($arr, count($arr) + $cols - $rem, '-');
    }
    
    $out .= '<table border=1>';
    foreach($arr as $key => $val)
    {
        if ($key % $cols == 0)
            $out .= '<tr>'."\n";
            
        $out .= '<td>'.$val.'</td>'."\n";
        
        if ($key % $cols == $cols - 1)
            $out .= '</tr>'."\n";
    }
    return  $out.'</tr></table>';
}




Theme © iAndrew 2016 - Forum software by © MyBB