gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 00:07:04 25 4
gpt4 key购买 nike

我在 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.

最佳答案

我想这就是您正在寻找的:

<?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;
?>

希望对你有帮助!

关于php - Foreach:为指定行数添加换行符(段落)的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24443571/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com