gpt4 book ai didi

php - 在每组的某个数组元素后添加一个div

转载 作者:行者123 更新时间:2023-11-28 01:42:35 25 4
gpt4 key购买 nike

PHP:

$rows = $users->fetchAll(PDO::FETCH_ASSOC);
$arrayByGroup = array();

$id = null;
foreach ($rows as $r) {
if($id != $r['id_group']) {
if (!is_null($id)) {
echo '</div>';
}
$id = $r['id_group'];
echo '<div class="id_group_' . $id . '">';
}
echo "<div>".$r["comments"]."<br>Written by ".$r["name"]."</div>";

}
echo '</div>'

我一直在使用来自 thread 的上述代码根据 id_group 字段中的公共(public)值对返回的数据进行分组。我得到这个输出

 <div class="id_group_1"> 
<div>comment from group 1</div>
<div>comment from group 1</div>
<div>comment from group 1</div>
</div>

<div class="id_group_2">
<div>comment from group 2</div>
<div>comment from group 2</div>
<div>comment from group 2</div>
<div>comment from group 2</div>
<div>comment from group 2</div>
</div>

现在我想在每组的第四个数组元素后面添加一个.more_comments div,理想的输出应该是这样的

 <div class="id_group_1"> 
<div>comment from group 1</div>
<div>comment from group 1</div>
<div>comment from group 1</div>
<div class="more_comments">
<div>comment from group 1</div>
<div>comment from group 1</div>
</div>
</div>

<div class="id_group_2">
<div>comment from group 2</div>
<div>comment from group 2</div>
<div>comment from group 2</div>
<div class="more_comments">
<div>comment from group 2</div>
<div>comment from group 2</div>
</div>
</div>

我不知道将计数器放在代码中的什么位置才能获得该结果。以下尝试不根据分组包装元素。谁能告诉我如何获得该输出?

$rows = $users->fetchAll(PDO::FETCH_ASSOC);
$arrayByGroup = array();
$counter = 0;
$id = null;
foreach ($rows as $r) {
if($id != $r['id_group']) {
if (!is_null($id)) {
echo '</div>';
}
$id = $r['id_group'];
echo '<div class="id_group_' . $id . '">';
}
echo "<div>".$r["comments"]."<br>Written by ".$r["name"]."</div>";

if($counter == 4)
{
echo "More Comments";
}
$counter++;

}
echo '</div>'

最佳答案

如果只是为了显示一些信息,您可以使用一些 JavaScript。

$(document).ready(function(){

var min_comment = 3;

$('.group').each(function(){
var children = $(this).children();
if(children.length > min_comment){
$(this).html('');
for(var i=0; i<min_comment; i++){
$(this).append(children[i]);
}
$(this).append('<div class="more-comments"></div>');
for(var j=min_comment; i!=children.length; i++){
$(this).find('.more-comments').append(children[i]);
}
}
});
});

http://jsfiddle.net/caboche_maxime/QjDd9/

看看这个 jsfidle。它应该做你想做的事

关于php - 在每组的某个数组元素后添加一个div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25019818/

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