Remind Login
Remind Login

Reputation: 15

data from database with foreach - from top to down

database:

id | name
1  | aaa
2  | bbb
3  | ccc
.. | ...
250| zz3

foreach ($datafromdb as $value){
  echo $value->name();
}

this show me:

aaa bbb  ccc  ... zz3

from left to right

if 

<table>
 <tr>
    foreach ($datafromdb as $value){
      echo '<td>' . $value->name() . '</td>';
    }
  </tr>
</table>

show:

aaa
bbb
ccc
...
zzz3

how can i make table 12x12 ?

aaa aaa1 bbb2
bbb aaa2 bbb2
... aaa3 bbb3
... ...  ....
zzz zzz2 zzz4

first from top to down (12x), then next column and again from top to down (12x) etc 12x

i have show this value from left to right, left to right, left to right etc, but i would like from top to down, top to down, top to down etc

Upvotes: 1

Views: 766

Answers (5)

Franquis
Franquis

Reputation: 743

Daniel Cherrington's code is good, but with only PHP just do:

<?php
$data = range(1,240);
$tab = array();
$max = 12;
for($i=0;$i<sizeof($data);$i++){
    $tab[($i % $max)][] = $data[$i];
}

echo "<table border='1'>";
foreach($tab as $line){
    echo "<tr>";
    foreach($line as $row){
        echo "<td>".$row."</td>";
    }
    echo "</tr>";
}
echo "</table>";
?>

Upvotes: 0

Daniel Cherrington
Daniel Cherrington

Reputation: 111

You could try creating tables side by side (float them using css)

  $index=0;
    foreach ($data as $value)
    {
      if($index == '12') $index = 0;

      if($index == 0) echo '<table style="float:left;">';
      echo '<tr>' ;
      echo '<td>' . $value . '</td>';
      echo '</tr>' ;
      if($index==11) echo '</table>' ;
      $index ++;
    }

Upvotes: 1

Naor
Naor

Reputation: 24093

Look, I don't exactly know php but this is what I can think of:

<table>
    <tr>
    var counter=0;
    foreach ($datafromdb as $value){
        if (i%12==0) { echo '<td>'; }
        echo $value->name()+'<br/>';
        if (i%12==0) { echo '</td>'; }
        counter++;
    }
    </tr>
</table>

Hope this helps!

Upvotes: 0

TJHeuvel
TJHeuvel

Reputation: 12608

<?php

$data = range(1,16);

$maxColumns = 4;
$maxRows = 4;

?>

<table>

    <? for($r = 0; $r < $maxRows; $r++) { ?>
        <tr>
            <? for($c = 0; $c < $maxColumns; $c++) { ?>
                <td><? echo $data[($c*$maxColumns)+$r]?></td>
            <? }?>
        </tr>
    <? } ?>
</table>

You might want to check if the data actually exists before echoing it.

Upvotes: 0

user517491
user517491

Reputation:

<table>
        $index=0;
        foreach ($datafromdb as $value)
        {
          if($index%12==0) echo '<tr>' ;
          echo '<td>' . $value->name() . '</td>';
          if($index%12==0) echo '</tr>' ;
        }
</table>

Upvotes: 1

Related Questions