tags:

views:

408

answers:

2

Hi, 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!

A: 

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++;
}
?>
Arthur Frankel
Thanks Arthur, this works perfect as well! You rock. The only difference wih Pascal's solution is that you must have the same files on each folder. If, say, I have less files in the thumbs folder, file pic_1.jpg points to file pic_2.jpg if pic1.jpg doesn't exist.
Luis B.
+1  A: 

Your two imbricated foreach actually mean :

  • for each one of the 3 images not in thumbs
  • loop over the 3 images in 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++;
}
Pascal MARTIN
Gee, I posted the question, went for a coffee and when I got back my question was answered.Thanks a lot Pascal! You saved my life. Had been trying to solve this for 2 weeks and didn't want to bother anyone until I was almost dead.It works perfect!
Luis B.
You're welcome :-) Have fun ! (and a coffee break is always good for productivity ;-) )
Pascal MARTIN