【问题标题】:Add a div after a certain array element in each group在每组中的某个数组元素之后添加一个div
【发布时间】:2014-09-21 02:11:20
【问题描述】:

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

【问题讨论】:

  • 拜托拜托拜托不要写意大利面条代码,使用模板引擎来处理这些东西:(
  • @FezVrasta,不熟悉模板引擎。他们可以使用这种 if 条件吗?
  • 取决于您选择的,是的,但即使不是,您也应该准备好内容以提供给您的模板,并且模板中不应包含太多逻辑。

标签: php html loops foreach


【解决方案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/

看看这个jsfile。它应该做你所寻求的

【讨论】:

    猜你喜欢
    • 2020-06-06
    • 2020-12-09
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 2015-09-29
    • 1970-01-01
    • 1970-01-01
    • 2021-03-20
    相关资源
    最近更新 更多