简体   繁体   中英

Split 1 Loop Into 2 Column in PHP

I made tables using foreach loop, it looks like this

在此处输入图片说明

How do i split it into two column like this:

在此处输入图片说明

Use modulo to conditionally split your elements into two different groups:

<?php
for ($i = 0; $i < 10; $i++) {
    if ($i % 2 == 0) {
        echo "<div class='left'>$i</div>";
    } else {
        echo "<div class='right'>$i</div>";
    }
}
?>

And then use CSS to float the columns next to each other:

.left {
  float: left;
}
.right {
  float: right;
}
.left, .right {
  width: 50%;
}

With the help of for loop, increasing by 2. This also reduce the number of iteration.

PHP

$arr = range(1, 10);
echo '<table>';
for ($i = 0; $i < count($arr); $i += 2)
{
    echo '<tr>';
    echo "<td>{$arr[$i]}</td>";
    echo "<td>{$arr[$i + 1]}</td>";
    echo '</tr>';
}
echo '</table>';

CSS:

td {
    border: 2px solid #000;
}

Print it out simply in PHP:

<div class="grid">
<?php
    foreach($tables as $table){
        echo "<div>".$table."</div>";
    }
?>
</div>

Yields:

<div class="grid">
    <div>Table Code</div>
    <div>Table Code</div>
    <div>Table Code</div>
    <div>Table Code</div>
</div>

Then style with CSS Grid:

 .grid{ display: grid; grid-template-columns: 1fr 1fr; } .grid > div{ border: blue 3px dashed; padding: 25px; } 
 <div class="grid"> <div>Table Code</div> <div>Table Code</div> <div>Table Code</div> <div>Table Code</div> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM