问题描述
我正在使用foreach来循环显示图像。最多有四个图像和最少的一个图像。
例如,如果有两个图像(=两个循环),我想告诉foreach他需要再循环两次,并呼应一些占位符的图片。
我的foreach:
<?php foreach($ users as $ k => $ v){?>
< img src =/ images / user_<?php echo $ k;?> .jpgalt =title =/>
<?php}?>
输出(两个循环):
< img src =/ images / user_0.jpgalt =title =/>
< img src =/ images / user_1.jpgalt =title =/>
但新脚本应输出:
< img src =/ images / user_0.jpgalt =title =/>
< img src =/ images / user_1.jpgalt =title =/>
< img src =/ images / user_placeholder.jpgalt =title =/>
< img src =/ images / user_placeholder.jpgalt =title =/>
不要忘记$ users可以有x个条目(0-4)
使用可以根据需要填充所有项目(因为它们全部相同),然后将其打印出来。
<?php foreach($ users as $ k => $ v){?>
< img src =/ images / user_<?php echo $ k;?> .jpgalt =title =/>
<?php}?>
<?php
echo implode('',array_fill(0,count($ users),'placeholder image HTML'));
当然,您也可以使用另一个 foreach
在每个迭代中打印占位符图像HTML
$ b 更新事实证明,还有一个更好的方法:
$ b $ $ p $
echo str_repeat('placeholder image HTML',count($ users));
PHP真的有许多功能需要记住。 :)
I am using a foreach to loop through image. There are maximum four images and minimum 1 image.For example if there are two image (= two loops) i want to tell the foreach he needs to loop two times again and echo some placeholder pictures.
Heres my foreach:
<?php foreach($users as $k => $v) {?>
<img src="/images/user_<?php echo $k; ?>.jpg" alt="" title="" />
<?php } ?>
Outputs (two loops):
<img src="/images/user_0.jpg" alt="" title="" />
<img src="/images/user_1.jpg" alt="" title="" />
but the new script should output:
<img src="/images/user_0.jpg" alt="" title="" />
<img src="/images/user_1.jpg" alt="" title="" />
<img src="/images/user_placeholder.jpg" alt="" title="" />
<img src="/images/user_placeholder.jpg" alt="" title="" />
dont forget its possible that $users can have x entries (0-4)
Use array_fill
to fill an array with as many items as needed (since they are all going to be identical) and then print them out.
<?php foreach($users as $k => $v) {?>
<img src="/images/user_<?php echo $k; ?>.jpg" alt="" title="" />
<?php } ?>
<?php
echo implode('', array_fill(0, count($users), 'placeholder image HTML'));
Of course instead of this cuteness you could also use another foreach
that prints placeholder image HTML
in each iteration.
Update: It turns out there's an even better method:
echo str_repeat('placeholder image HTML', count($users));
PHP really has too many functions to remember. :)
这篇关于PHP foreach循环x次,并添加占位符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!