Using PHP loop to add Bootstrap rows and proper column numbers to elements

后端 未结 6 1614
一整个雨季
一整个雨季 2020-12-08 22:06

I\'m trying to create the following front-end using a PHP loop and Twitter Bootstrap\'s 12 column grid system:

The HTML output is:

6条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-08 22:56

    I liked your question because I'm working on a very similar situation. Since other answers are a bit longer, I decided to leave mine here for your consideration. For me, the less variables you use, the best the solution is.

    BootstrapContentArranger.php

     0) {        // while still have items
            $cell = 0;
            if ($rows > 1) {        // if not last row...
                echo '
    '.PHP_EOL; while ($cell < 3) { // iterate with 3x4 cols echo '
    Content
    '.PHP_EOL; $cell++; } echo "
    ".PHP_EOL; $rows--; // end a row } elseif ($rows == 1 && $lr > 0) { // if last row and still has items echo '
    '.PHP_EOL; while ($lrc > 0) { // iterate over qnt of remaining items $lr == 2 ? // is it two? print('
    Content
    '.PHP_EOL) : // makes 2x6 row print('
    Content
    '.PHP_EOL); // makes 1x12 row $lrc--; } echo "
    ".PHP_EOL; break; } else { // if round qnt of items (exact multiple of 3) echo '
    '.PHP_EOL; while ($cell < 3) { // iterate as usual echo '
    Content
    '.PHP_EOL; $cell++; } echo "
    ".PHP_EOL; break; } $items--; // decrement items until it's over or it breaks } }

    Test Cases

    BootstrapContentArrange(3);
    BootstrapContentArrange(11);
    BootstrapContentArrange(1);
    
    1. 3 items, outputs:

    Content
    Content
    Content

    1. 11 items, outputs:

    Content
    Content
    Content
    Content
    Content
    Content
    Content
    Content
    Content
    Content
    Content

    1. A single item, outputs:

    Content

    Note: you can remove the PHP_EOL, I used it to read the source better.

提交回复
热议问题