我不是高级php程序员,所以我需要一些帮助。
我正在尝试使用指向完整图像和thummail的链接来回显列表项。
这是想要的结果:
<li>
<a href="fullimagepath1">
<img src="thumnailpath1" />
</a>
</li>
<li>
<a href="fullimagepath2">
<img src="thumnailpath2" />
</a>
</li>
<li>
<a href="fullimagepath3">
<img src="thumnailpath3" />
</a>
</li>
...
这是我正在使用的代码
<?php
$images = rwmb_meta( 'product_gallery', 'type=image&size=press-thumb' );
$fullimages = rwmb_meta( 'product_gallery', 'type=image&size=productfull-thumb' );
foreach ( $fullimages as $fimages)
foreach ( $images as $image)
{
echo "<li><a class='thumb' href='{$fimages['url']}'><img src='{$image['url']}' /></a></li>";
} ?>
问题是我得到了缩略图,但乘以了实际结果的数量。如果我的图库有3个缩略图,结果将是9个缩略图,如果我有5个缩略图,将得到25个。
如何修复代码?提前感谢!
这是因为这条线foreach ( $fullimages as $fimages)
正在触发内部循环。
由于您可能有3个图像,并且两个数组都包含三个项目数组,所以循环将在一个更大的循环中运行3次,该循环也将执行3次。所以你有9个项目。
在您的代码上
foreach ( $fullimages as $fimages) //Because of this loop next statement executes
foreach ( $images as $image) {
echo "<li><a class='thumb' href='{$fimages['url']}'><img src='{$image['url']}' /></a></li>";
}
你可能想要的是?
foreach ( $fullimages as $k => $fimages) {
// ^ Get the index of the array
echo "<li><a class='thumb' href='{$fimages['url']}'>
<img src='{$images[$k]['url']}' /></a></li>";
// ^ Use that key to find the thumbnail from $images array
}
尝试此代码
foreach ( $fullimages as $fimages)
{
foreach ( $images as $image)
echo "<li><a class='thumb' href='{$fimages['url']}'><img src='{$image['url']}' /></a></li>";
} ?>
我建议存储这样的图像:
$images = array(
'fullpath' => '...'
'thumbpath' => '...'
)
而不是两个单独的阵列。并且只在一个阵列上循环。
或者使用类似next($array)
、current($array)
的迭代器函数来同时对两个数组进行迭代。
您可以使用和迭代
for ($i=0;$i<count($images);$i++){
echo $images[$i]['url'], $fullimages[$i]['url'];
}
或者使用array_map
array_map(function($image, $fullimage){
echo $image['url'], $fullimage['url'];
}, $images, $fullimages);