Jump to content

foreach not getting to work


pwired
 Share

Recommended Posts

I installed pw 2.5 and instead of outputting 1 picture I want to output

3 pictures on top of the sidebar. This is the original code that outputs 1 picture:

if(count($page->images)) {
    // if the page has images on it, grab one of them randomly...
    $image = $page->images->getRandom();
    // resize it to 400 pixels wide
    $image = $image->width(400);
    // output the image at the top of the sidebar
    $sidebar = "<img src='$image->url' alt='$image->description' />" .
        "<blockquote>$image->description</blockquote>" .
        $page->sidebar;    
}

Here I changed the code a bit to output 2 pictures on top of the sidebar:

if(count($page->images)) {
    // if the page has images on it, grab the first two of them...
    $image1 = $page->images->first();
    $image2 = $page->images->eq(1);
    // resize it to 400 pixels wide
    $image1 = $image1->width(400);
    $image2 = $image2->width(400);
    // output the image at the top of the sidebar
    $sidebar = "<img src='$image1->url' alt='$image1->description' />" .
        "<blockquote>$image1->description</blockquote>" ."<img src='$image2->url' alt='$image2->description' />" .
        "<blockquote>$image2->description</blockquote>" .
        $page->sidebar;    
}

The above is working but of course it should be working with a foreach

which I tried here:

if(count($page->images)) {
    // if the page has images on it, loop through them...
                  foreach($page->images as $image) {
        $image = $image->width(400);
        $pictures = "<img src='$image->url' alt='$image->description' />" .
        "<blockquote>$image->description</blockquote>" ;
                            }
    
    // output the images at the top of the sidebar
    $sidebar = $pictures . $page->sidebar;    
}

However this code with the foreach only shows the last picture while I have 3 of them

Anyone knows what is wrong ?

Edited by adrian
codified code blocks :)
Link to comment
Share on other sites

You are overwriting the $pictures variable in each loop iteration. It will only ever have the last image in it that way. You should concatenate instead. Something like this...

if(count($page->images)) {
    
    $pictures = '';

    // if the page has images on it, loop through them...
    foreach($page->images as $image) {
        $image = $image->width(400);
        $pictures .= "<img src='$image->url' alt='$image->description' />" .
        "<blockquote>$image->description</blockquote>";
    }
    
    // output the images at the top of the sidebar
    $sidebar = $pictures . $page->sidebar;    
}

Note that it is now $pictures .= "..." rather than $pictures = "..."

  • Like 2
Link to comment
Share on other sites

  • 4 weeks later...
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...