dpuuys2198
2013-07-29 18:10
浏览 114
已采纳

将php foreach循环的结果存储为数组

I am using a foreach loop to generate a set of thumbnail links. I am using Wordpress and for one reason or another the place my PHP is executing is not the place I would like to render the list. So my question is: can I replace the echo statement with something that will store all of the generated html (for each image, not just the last one) and allow me to generate it further down the same page?

Thanks for any help. Here's my php so far:

foreach ($gallery_images as $galleryID) {
    $attachment = get_post( $galleryID );

    $thumb_img = wp_get_attachment_image_src( $galleryID, 'thumbnail' );    //thumbnail src
    $full_img = wp_get_attachment_image_src( $galleryID, 'full' );  //full img src

    echo '<a href="' . $full_img[0] . '" id="description-button-' . $gallery_images_count . '" class="thumbLink" target="_blank"><img src="' . $thumb_img[0] .'"></a>';

    $gallery_images_count++;

}//end forEach
  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • doujiao0110 2013-07-29 18:13
    已采纳

    You can store the results to an array so that you can "echo" the results later:

    $links = array();
    foreach ($gallery_images as $galleryID) {
        $attachment = get_post( $galleryID );
    
        $thumb_img = wp_get_attachment_image_src( $galleryID, 'thumbnail' );    //thumbnail src
        $full_img = wp_get_attachment_image_src( $galleryID, 'full' );          //full img src
    
        $links[] = '<a href="' . $full_img[0] . '" id="description-button-' . $gallery_images_count . '" class="thumbLink" target="_blank"><img src="' . $thumb_img[0] .'"></a>';
    
        $gallery_images_count++;
    
    }
    

    And then later in your code, you can print it out:

    echo implode("
    ", $links);
    
    已采纳该答案
    评论
    解决 1 无用
    打赏 举报
  • douyuan1752 2013-07-29 18:12
    $arr = array();
    foreach(...) {
       $arr[] = '<a href=........';
    }
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题