php查询if语句

时间:2015-11-25 17:47:53

标签: php arrays if-statement while-loop

我有以下代码,其中包含以下变量集numberofColumns = 2numberArticles = 10,将为文章创建2列,文章顺序从左到右(column1到column2)在页面下方

我想在每第2篇文章之后添加一些代码</div><div class="whatever">

非常感谢任何帮助。

        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>';
        }

1 个答案:

答案 0 :(得分:0)

我总是使用模数运算符(%)来确定我当前的索引是否是n行之一。 $ index%2每隔一行返回0。 $ index%3每隔三行返回0,依此类推。 http://php.net/manual/en/internals2.opcodes.mod.php

该页面上的第一条评论表明,当您只需要确定奇数或偶数时,按位运算会更有效。所以,$ index&amp; 1(单数)是!$ index%2(单数)的更快替代。

相关问题