RedGiant
RedGiant

Reputation: 4748

Add a div after a certain array element in each group

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

I've been using the above code from this thread to group the returned data based on the common values in the id_group field. I'm getting this output

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

Now I want to add a .more_comments div after the forth array element in each group, the ideal output should be like this

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

I don't know where to put the counter in the code to get that result. The following attempt doesn't wrap the elements based on the grouping. Can anyone show me how to get that output?

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

Upvotes: 2

Views: 660

Answers (1)

Maxime Caboche
Maxime Caboche

Reputation: 49

If it's just for displaying some informations you can use some 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/

Just look on this jsfidle. It's should do what you seek

Upvotes: 1

Related Questions