while listing result of 4 in 4 within div

5

How do I list the result of a sql query so that a 4-by-4 line is inside a div.

Ex. expected result:

<div class="row">
    <span>1</span>
    <span>2</span>
    <span>3</span>
    <span>4</span>
</div>

<div class="row">
    <span>5</span>
    <span>6</span>
    <span>7</span>
    <span>8</span>
</div>

<div class="row">
    <span>9</span>
    <span>10</span>
</div>

Test:

$count = 0;
while ($count <= 10) {
    if ($count % 4) {
        echo '<div class="row"><span>'.$count.'</span></div>';
    }

    $count++;
}
    
asked by anonymous 12.12.2015 / 18:42

2 answers

5

What is missing is to isolate the divs .row of elements <span> or if span appears independent of being % 4 then it should neither be within while and % 4 should always be compared to 1 or 0 (as a suggestion of @Bacco to simplify we start comparing with % 4 zero):

<?php
$count = 0;

echo '<div class="row">', PHP_EOL;

while ($count <= 10) {
    if ($count > 0 && $count % 4 === 0) {//A cada quatro deve fechar o .row e abrir novamente
        echo '</div>', PHP_EOL, PHP_EOL, '<div class="row">', PHP_EOL;
    }

    echo '<span>', $count, '</span>', PHP_EOL;

    $count++;
}

echo '</div>';

One important thing is that your code is not generating 10 items, but 11 because it starts at zero, so if the increment starts from 1 then the code would be simpler, since the quantity would be 10, is greater than 1:

<?php
$count = 1;

echo '<div class="row">', PHP_EOL;

while ($count <= 10) {
    if ($count > 1 && $count % 4 === 1) {//A cada quatro deve fechar o .row e abrir novamente
        echo '</div>', PHP_EOL, PHP_EOL, '<div class="row">', PHP_EOL;
    }

    echo '<span>', $count, '</span>', PHP_EOL;

    $count++;
}

echo '</div>';
    
12.12.2015 / 18:58
7


This release has logic similar to the author's attempt and @Guilherme's response, using % . The difference is that the calculation of the module was done on 2 separate lines, to avoid repeating the echo s of div :

$count = 10;
$group = 4;

for ( $i = 1; $i <= $count; ++$i ) {
    if ( ( $i - 1 ) % $group == 0 ) echo '<div class="row">';
    echo '<span>'.$i.'</span>';
    if ( $i == $count || $i % $group == 0 ) echo '</div>';
}

See working at IDEONE .


Here's an alternative with two loops , which can be adapted to more complex scenarios:

    $count = 10;
    $group = 4;

    for ( $i = 1; $i <= $count; $i += $group ) {
        echo '<div class="row">';
        for ( $j = 0; $j < $group && $j + $i <= $count ; $j++ ) {
            echo '<span>'.($j + $i).'</span>';
        }
        echo '</div>';
    }

See working at IDEONE .

    
12.12.2015 / 18:52