3D-kreativ
3D-kreativ

Reputation: 9309

How to divide uneven numbers of images for columns

I have a layout with four column and I want to add images even to each column as possible. No problem if I have 60 images, then I would have 15 images in each column, but what if I have 43 or 55 or any other uneven number of images!? If I divide 55 to 4 i get 13.75. How can I calculate to get a result like 14 + 14 + 14 + 13 ?

column 1 = 14

column 2 = 14

column 3 = 14

column 4 = 13

Upvotes: 1

Views: 95

Answers (2)

James Wu
James Wu

Reputation: 58

First, calculate the minimum number of images per column. Then calculate the remainder. Then spread the remainder to the first N columns.

Here is how to do it in Javascript. The function split() is generalized for any number of columns.

function split(n_images, num_of_columns) {

    var min = Math.floor(n_images / num_of_columns);
    var remainder = n_images % num_of_columns;
    var columns = Array.apply(null, Array(num_of_columns)).map(function(value, index) {
        return (index < remainder? min + 1: min);
    });
    return columns;
}

var n_images = 55;
var num_of_columns = 4;
var columns = split(n_images, num_of_columns);

Upvotes: 0

toomanyredirects
toomanyredirects

Reputation: 2002

First, using ceil to round up, calculate the number of images per column:

$number_of_columns = 4;
$images_per_column = ceil(count($images) / $number_of_columns);

Then, use array_chunk to split the $images array into chunks of that size (the last one will come out smaller):

$image_columns = array_chunk($images, $images_per_column);

You will then have a multidimensional array - an array with 4 arrays of images inside it.

You can loop over it like so:

<?php foreach ($image_columns as $images_in_column): ?>
<div class="column">
  <?php foreach ($images_in_column as $column_image): ?>
    <img src="<?php echo $column_image; ?>" />
  <?php endforeach; ?>
</div>
<?php endforeach; ?>

Upvotes: 1

Related Questions