Dynamic grid columns in Bootstrap

So, I want to apply the grid style of Bootstrap to the a number of div tag in my php code . Here is one way to achieve that:

1. Using this javascript snippet in the template:

$(document).on("ready", function() {
  $.each(['xs', 'sm', 'md', 'lg'], function(idx, gridSize) {
    $('.col-' + gridSize + '-auto:first').parent().each(function() {
      //we count the number of childrens with class col-md-6
      var numberOfCols = $(this).children('.col-' + gridSize + '-auto').length;
      if (numberOfCols > 0 && numberOfCols < 13) {
        minSpan = Math.floor(12 / numberOfCols);
        remainder = (12 % numberOfCols);
        $(this).children('.col-' + gridSize + '-auto').each(function(idx, col) {
          var width = minSpan;
          if (remainder > 0) {
            width += 1;
            remainder--;
          }
          $(this).addClass('col-' + gridSize + '-' + width);
        });
      }
    });
  });
});


2. Then in my template i just need to assign the "col-auto" to the div:

<?php 
$blogs = get_blogs_by_school('es');
foreach($blogs as $class => $cblogs) {
?>
<div class="col-md-auto">
<h3><?php echo $class ?>:</h3>
<ul>
<?php 
foreach($cblogs as $blog) {
?>
<li>
<a href="http://<?php echo $blog['domain'] . $blog['path']; ?>" target="_blank">
<?php 
$mail = get_blog_option($blog['blog_id'], 'admin_email');
$user_from_email = get_user_by('email', $mail);
$fullname = $user_from_email->first_name . ' ' .  $user_from_email->last_name;
if(!empty(trim($fullname))) {
echo $fullname;
} else {
echo $user_from_email->display_name;
}
?>
</a>
</li>
<?php 
}
?>
</ul>
</div>
<?php 
}
?>

For example, if my data ($blogs) has 2 classes ($class), there will be 2 div tags which have "col-md-6" class.

Reference:
http://duncan.mac-vicar.com/2013/11/05/dynamic-grid-columns-with-twitter-bootstrap/