Foreach:为指定行数添加换行符(段落)的正确方法

时间:2014-06-27 03:41:04

标签: php mysql foreach while-loop

我在mysql数据库中有一堆随机句子,我没有问题将它们拉出来并使用下面的代码显示它们,但是,我对这个下一个过程感到困惑。

如何为每X行添加nl或封装在

标签中?选定的行已经限制为14(任意),我的目标是获取这14行并每隔3或4添加换行符(也是任意的),这样它们看起来更流畅。

    <?php 
include $_SERVER['DOCUMENT_ROOT'] . '/dbConnect.php';
$q = $dbc->query("SELECT DISTINCT sentence FROM sentences ORDER BY rand() LIMIT 14");

    while($r = $q->fetch_array(MYSQLI_ASSOC)):
    foreach($r as $value) {
$value = str_replace('$keyword', '<b>replaced keyword</b>', $value);
echo $value." ";  
    }

    endwhile;

?>

上面的代码很适合这样做:

示例输出:

This is a complete sentence that I'm outputting to the page.
This is a complete sentence that I'm outputting to the page.
This is a complete sentence that I'm outputting to the page.
This is a complete sentence that I'm outputting to the page.
This is a complete sentence that I'm outputting to the page.
This is a complete sentence that I'm outputting to the page.
This is a complete sentence that I'm outputting to the page.

但是,我希望它能够做更多这样的事情,而不会创建一个低效的3块相同代码,限制为3,2和4或类似。

This is a complete sentence that I'm outputting to the page.
This is a complete sentence that I'm outputting to the page.
This is a complete sentence that I'm outputting to the page.

This is a complete sentence that I'm outputting to the page.
This is a complete sentence that I'm outputting to the page.

This is a complete sentence that I'm outputting to the page.
This is a complete sentence that I'm outputting to the page.
This is a complete sentence that I'm outputting to the page.
This is a complete sentence that I'm outputting to the page.

2 个答案:

答案 0 :(得分:0)

我想这就是你要找的东西:

<?php 
include $_SERVER['DOCUMENT_ROOT'] . '/dbConnect.php';
$i=0; $j=0;
$seq=array(3, 2, 4);
$q = $dbc->query("SELECT DISTINCT sentence FROM sentences ORDER BY rand() LIMIT 14");

    while($r = $q->fetch_array(MYSQLI_ASSOC)):
    foreach($r as $value) {
         $value = str_replace('$keyword', '<b>replaced keyword</b>', $value);
         echo $value."<br>";
         if($i==$seq[$j])
         {
             echo "<br>";
             $j++;
             $i=0;
             if($j==count($seq)) $j=0;
          } else {
             $i++;
          }
    }
    endwhile;
?>

希望它有所帮助!

答案 1 :(得分:0)

以下是我对您提问的方法:

$numberOfSentencesPerParagraph = 4; // specify
$totalNumberOfSentences = 14; // or use a count function to calculate the number of returned MySQL records // or make this equal to a new variable you will introduce in your SQL query (after `LIMIT`)
while($r = $q->fetch_array(MYSQLI_ASSOC)):
    $theCounter = 1;
    foreach($r as $value) {
        $value = str_replace('$keyword', '<b>replaced keyword</b>', $value);
        echo $value." ";  
        $theCounter++;
        if(($theCounter % $numberOfSentencesPerParagraph) == 0){
            echo "<br>";
        }
    }
endwhile;

它只是运行一个计数器&#39;当它的值是变量$numberOfSentencesPerParagraph的倍数时,echo就会出现换行符。