普通网友 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 weditor无法连接模拟器Local server not started, start with?
  • ¥20 6-3 String类定义
  • ¥15 嵌入式--定时器使用
  • ¥20 51单片机学习中的问题
  • ¥30 Windows Server 2016利用兩張網卡處理兩個不同網絡
  • ¥15 Python中knn问题
  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上