Reputation:
I need to load images from 2 different folders, each thumbnail has its associated large version (same name, different folder).
I have 3 files in the large pics folder and 3 files in the thumbs folder and I'm getting 9 links! Each thumbnail gets repeated 3 times or x times the quantity of pics in the main folder
This is the code:
<?php
foreach (glob("images/*.jpg") as $large)
foreach (glob("images/thumbs/*.jpg") as $thumb)
{
echo ("<div class='thumbnail'><a href='$large'><img src='$thumb'/></a></div>");
}
?>
If I reverse the order of the foreach glob lines I get links x times the quantity of thumbnails. I hope I've made myself understood, I'm new to this.
Thanks!
Upvotes: 0
Views: 7164
Reputation: 400972
Your two imbricated foreach actually mean :
thumbs
thumbs
So, 9 total iterations :-)
If you want to loop over the images not in thumbs, you only need the first one.
If you only want to loop over the images in thumbs, you only need the second one.
If you want all images : large+thumb at the same time, and if large images have the same name as thumbs, you only need one loop to get the names of the files.
And when you have that name, you prepend it with "images/thumbs/
" or "images/
", depending on which image you want.
Not tested, but something like this might help :
$counter = 0;
foreach (glob("images/thumbs/*.jpg") as $pathToThumb)
{
$filename = basename($pathToThumb);
$pathToLarge = 'images/' . $filename;
echo ("<div class='thumbnail'><a href='$pathToLarge'><img src='$pathToThumb'/></a></div>");
$counter++;
}
Upvotes: 3
Reputation: 4705
I suppose one solution would be to just load 'glob' return into an array and reference it that way:
<?php
$largeArray = glob("images/*.jpg");
$counter = 0;
foreach (glob("images/thumbs/*.jpg") as $thumb)
{
echo ("<div class='thumbnail'><a href='$largeArray[$counter]'><img src='$thumb'/></a></div>");
$counter++;
}
?>
Upvotes: 0