普通网友 2013-07-29 18:10
浏览 136
已采纳

将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条)

报告相同问题?

悬赏问题

  • ¥15 matlab有限元法求解梁带有若干弹簧质量系统的固有频率
  • ¥15 找一个网络防御专家,外包的
  • ¥100 能不能让两张不同的图片md5值一样,(有尝)
  • ¥15 informer代码训练自己的数据集,改参数怎么改
  • ¥15 请看一下,学校实验要求,我需要具体代码
  • ¥50 pc微信3.6.0.18不能登陆 有偿解决问题
  • ¥20 MATLAB绘制两隐函数曲面的交线
  • ¥15 求TYPCE母转母转接头24PIN线路板图
  • ¥100 国外网络搭建,有偿交流
  • ¥15 高价求中通快递查询接口