简体   繁体   中英

php query if statement within while statement

I have the following code which with the following variables set numberofColumns = 2 and numberArticles = 10 , will create 2 columns for articles, the article order is from left to right (column1 to column2) going down the page.

Id just like to add some code </div><div class="whatever"> after every 2nd article.

Any help would be much appreciated.

        if ($numberColumns >= 1) {
            $columnArticles = intval(($numberArticles + $numberK2Articles) / $numberColumns);
        }

        $columns = array();
        for($columnIndex = 0; $columnIndex < $numberColumns; $columnIndex++) {
            $columns[$columnIndex] = '<div class="column col-' . ($columnIndex + 1) . '">';
        }

        $articleIndex = 0;
        while($articleIndex < count($articles)) {
            foreach ($columns as $columnIndex => $column) {
                if (isset($articles[$articleIndex])) {
                    $columns[$columnIndex] .= modCTRandomArticleHelper::getArticleHtml($params, $articles, $articleIndex);
                    $articleIndex++;
                }
            }
        }

        for($columnIndex = 0; $columnIndex < $numberColumns; $columnIndex++) {
            echo $columns[$columnIndex] . '</div>';
        }

I've always used the Modulus operator (%) to determine if my current index was one of n rows. $index % 2 returns 0 for every second row. $index % 3 returns 0 for every third row, and so on. http://php.net/manual/en/internals2.opcodes.mod.php

The first comment on that page suggests that a bitwise operation is more efficient when you just need to determine odd or even. So, $index & 1 (odd) is a faster alternative to !$index % 2 (odd).

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