【发布时间】:2018-05-20 23:07:02
【问题描述】:
大家好,我目前正在处理一个 foreach 循环,该循环从 Wordpress 后端的图库中提取图像。画廊工作正常,正如预期的那样,但是,我想防止出现重复的照片。
<?php if () $query->have_posts() ):
$thumbs = [];
?>
<?php
foreach( $query->posts as $gallery ):
$images = get_field('gallery_images', $gallery->ID);
if( $images ):
foreach( $images as $image ):
$cropped_img = aq_resize( $image['url'], 1024, 576, true, true, true );
$img_id[] = $image['ID'];
$thumbs[] = $cropped_img;
?>
与问题无关的 HTML
<?php endforeach; endif; endforeach; ?>
<?php foreach($thumbs as $thumbnail): ?>
<div class="gallery__thumb"><img src="<?= $thumbnail; ?>"></div>
<?php endforeach; ?>
这基本上就是我想要解决的问题。我想为图像 ID 添加两个变量,这样它们就不会在第一个代码块中重复。所以第一个 if/foreach 状态看起来像:
<?php if( $images ):
foreach( $images as $image ):
$cropped_img = aq_resize( $image['url'], 1024, 576, true, true, true );
$img_id[] = $image['ID'];
$do_not_duplicate[] = $image['ID'];
$thumbs[] = $cropped_img;
?>
其次是缩略图的following foreach
<?php foreach($thumbs as $thumbnail): ?>
<?php foreach($img_id as $img): ?>
<?php if ($img == $do_not_duplicate) : ?>
//do nothing
<?php else : ?>
<div class="gallery__thumb"><img src="<?= $thumbnail; ?>"></div>
<?php endif; ?>
<?php endforeach; endforeach; ?>
我遇到的问题是我得到了 22 张图像输出 23 次,因为有 22 张图像被拉出(有 1 张重复)。本质上,我正在尝试完成 22 张没有重复的图像。
任何见解将不胜感激,在此先感谢您。
【问题讨论】:
标签: php wordpress if-statement foreach