1

The problem is just logical... I'm trying to make a photo gallery getting the images url from a database... The problem is when I'm rendering in HTML. I'm using bootstrap to make the layout. Every row has 3 images, when I make a while to render the images I can't figure out how to render 3 images by row using just a loop.

I'm using PHP, but written some draft code just to be easier to explain.

I`m trying to do something like that:

 for(result in array){
    <div class="row tattos-row">
        <div class="col-sm">
            <img class="img-portifolio" src="result[URL]">
        </div>
    </div>
 }

I'm expectecting this result:

<div class="row tattos-row">
    <div class="col-sm">
        <img class="img-portifolio" src="url_1">
    </div>
    <div class="col-sm">
        <img class="img-portifolio" src="url_2">
    </div>
    <div class="col-sm">
        <img class="img-portifolio" src="url_3">
    </div>
</div>

<div class="row tattos-row">
    <div class="col-sm">
        <img class="img-portifolio" src="url_4">
    </div>
    <div class="col-sm">
        <img class="img-portifolio" src="url_5">
    </div>
    <div class="col-sm">
        <img class="img-portifolio" src="url_6">
    </div>
</div>

2 Answers2

1

Hey by the syntax looks like some templating tool but the logics would be something like this

<?php $chunks = array_chunk($data, 3); ?>
<?php foreach ($chunks as $chunk): ?>
    <div class="row tattos-row">
        <?php foreach ($chunk as $item): ?>
            <div class="col-sm">
                <img class="img-portifolio" src="<?= $item['url'] ?>">
            </div>
        <?php endforeach; ?>
    </div>
<?php endforeach; ?>

Check out the array_chunk method (https://www.php.net/manual/en/function.array-chunk.php) as it is what you need - you simply want to create groups of 3 items and then iterate over all groups, create the row and then iterate over the group elements to output each element. It's 2 foreach (or in your case for I guess) loops

Kārlis Ābele
  • 971
  • 4
  • 9
1

Solution is very simple. As you mentioned that, you have an array of images. You can set three images per row.

 <div class="container">
    <div class="row">
        <?php for($i=0;$i<count($array);$i++){?>
            <div class="col-sm-4">
                <img src="<?php echo $array[$i]?>" alt="">
            </div>
        <?php } ?>
    </div>
</div>

php code will be look like:

<?php $array = ['https://i.pravatar.cc/150?img=3','https://i.pravatar.cc/150?img=32','https://i.pravatar.cc/150?img=33','https://i.pravatar.cc/150?img=34','https://i.pravatar.cc/150?img=35'];?>
Shivani Sonagara
  • 1,299
  • 9
  • 21
  • This as well is not solving the actual problem. Please see the expected result added in the question... Visually it would probably be similar (except the bootstrap row paddings/margins etc.) but the DOM would not be as expected – Kārlis Ābele Jun 20 '19 at 05:55