【问题标题】:Store results of a php foreach loop as an array将 php foreach 循环的结果存储为数组
【发布时间】:2013-07-29 18:10:28
【问题描述】:

我正在使用 foreach 循环来生成一组缩略图链接。我正在使用 Wordpress,出于某种原因,我的 PHP 正在执行的地方不是我想要呈现列表的地方。所以我的问题是:我可以将 echo 语句替换为存储所有生成的 html 的内容(对于每个图像,而不仅仅是最后一个图像),并允许我在同一页面的下方生成它吗?

感谢您的帮助。到目前为止,这是我的 php:

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

【问题讨论】:

  • 而不是echo ... $html[] = ...?

标签: php arrays foreach


【解决方案1】:

您可以将结果存储到数组中,以便以后“回显”结果:

$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++;

}

稍后在您的代码中,您可以将其打印出来:

echo implode("\n", $links);

【讨论】:

  • 非常感谢您的帮助。只是出于兴趣,内爆是做什么的?
  • 它将数组的元素组合成一个大字符串,由分隔符(第一个参数)分隔。文档:php.net/manual/en/function.implode.php
【解决方案2】:
$arr = array();
foreach(...) {
   $arr[] = '<a href=........';
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-09
    • 2014-01-08
    • 1970-01-01
    • 2022-08-03
    • 1970-01-01
    • 2015-09-18
    相关资源
    最近更新 更多