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
字段中的常用值对返回的数据进行分组。我得到了这个输出
<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>'
答案 0 :(得分:1)
如果只是为了显示某些信息,您可以使用一些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。它应该做你想要的事情