July 5, 2013

PHP foreach multiple results

User2553099’s Question:

I´m not an advanced php coder so I need some help here.

I´m trying to echo list items with a link pointing to the full image and the thumnail.

This is the desired result:

<li>
    <a href="fullimagepath1">
        <img src="thumnailpath1" />
    </a>
</li>
<li>
    <a href="fullimagepath2">
        <img src="thumnailpath2" />
    </a>
</li>
<li>
    <a href="fullimagepath3">
        <img src="thumnailpath3" />
    </a>
</li>
...

This is the code I’m using

    <?php
        $images = rwmb_meta( 'product_gallery', 'type=image&size=press-thumb' );
    $fullimages = rwmb_meta( 'product_gallery', 'type=image&size=productfull-thumb' );
            foreach ( $fullimages as $fimages)
            foreach ( $images as $image)
                {
                    echo "<li><a class='thumb' href='{$fimages['url']}'><img src='{$image['url']}' /></a></li>";

    } ?>

The problem is that I’m getting the thumbnails but multiplied by the number of real results. If I have 3 thumbnails for my gallery the result will be 9 thumbnails, if I have 5 will get 25.

How can I fix the code?
Thanks in advance!

This is because of this line foreach ( $fullimages as $fimages) which is triggering inner loops.

Since you probably have 3 images and both array hold three items array, loop will run 3 times inside a bigger loop which will also execute 3 times. So you have 9 items.

On your code

foreach ( $fullimages as $fimages) //Because of this loop next statement executes
foreach ( $images as $image) {
  echo "<li><a class='thumb' href='{$fimages['url']}'><img src='{$image['url']}' /></a></li>";
}

What you probably want is?

foreach ( $fullimages as $k => $fimages) {
                      // ^ Get the index of the array
  echo "<li><a class='thumb' href='{$fimages['url']}'>
       <img src='{$images[$k]['url']}' /></a></li>";
                       // ^ Use that key to find the thumbnail from $images array
}

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!