Mark Fondy
Mark Fondy

Reputation: 3923

Foreach and columns

<?php
$arr = range(1,rand(40,120)); ?>

<table>

<?php
foreach ($arr as &$value) {
    echo '<tr><td>' . $value . '</td></tr>';
} ?>

</table>

This generate for me for example:

1
2
3
...
111

all in one columns. How can i make - when in first column are 25 rows then create new column, etc. For example:

1   26  51
2   27  ...
3
..
25  50

How can i make it? I can use DIV instead of table.

Upvotes: 0

Views: 705

Answers (3)

devdRew
devdRew

Reputation: 4571

EDITED

<?php

$rows = 25;
$arr = range(1, rand(40, 120));
$arr = array_merge($arr, array_fill(0, $rows - (count($arr) % $rows), null));
$cols = ceil(count($arr) / $rows);
$render = array();

echo '<table>' . "\n";
foreach ($arr as $i => $value) {
  $render[$i % $rows][] = $value;
  if (count($render[$i % $rows]) == $cols) {
    echo '  <tr>' . "\n" . '    <td>' . implode('</td>' . "\n" . '    <td>', $render[$i % $rows]) . '</td>' . "\n" . '  </tr>' . "\n";
  }
}
echo '</table>' . "\n";

?>

Upvotes: 1

Nicholas Kouvatsos
Nicholas Kouvatsos

Reputation: 643

<?php      
$arr = range(1,rand(40,120)); 
?>      

<div style="width:40px; float:left;">      

<?php      
foreach ($arr as $value) {      
    echo $value . '<br />';  
        if ($value % 25 == 0) {
            echo '</div><div style="width:40px; float:left;">';
        }
    } 
?>      

Upvotes: 1

Marc B
Marc B

Reputation: 360732

Vertically sorted columns of that sort (no pun intended) are a serious pain in html, since this arragement is a "top->bottom, left->right", while HTML tables by their nature are "left->right, top->bottom" instead.

To get around it, you have to do some offset math on the array indexes, so you can output by rows:

$arr = range(1,rand(40,120));
$rows = ceil(count($arr) / 3); // assuming 3 columns
for ($i = 0; $i < $rows; $i++) {
    echo <<<EOL
<tr>
   <td>{$arr[$i]}</td>    1, 2, 3, etc...
   <td>{$arr[$i+rows]}</td>  11, 12, 13, etc...
   <td>{$arr[$i+(2*$rows)]}</td> 21, 22, 23, etc...
</tr>
EOL;
}

This code probably won't work as is, but should give you the basic idea.

Upvotes: 1

Related Questions