简体   繁体   English

PHP foreach循环x次并添加占位符

[英]PHP foreach loop x times and add placeholder

I am using a foreach to loop through image. 我正在使用foreach遍历图像。 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. 例如,如果有两个图像(=两个循环),我想告诉foreach他需要再次循环两次并回显一些占位符图片。

Heres my foreach: 这是我的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) 不要忘记$ users可能有x个条目的可能性(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. 使用array_fill将所需的项目填充到数组中(因为它们将完全相同),然后将其打印出来。

<?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. 当然,除了这种可爱之外,您还可以使用另一个foreach在每次迭代中打印placeholder image HTML

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确实有太多功能需要记住。 :) :)

Use a counter... 使用柜台...

<?php
$counter = 0; 
foreach($users as $k => $v) {?> 
    <img src="/images/user_<?php echo $k; ?>.jpg" alt="" title="" />
<?php $counter++;  
} 
while{$counter < 4)
{?>
    <img src="/images/user_placeholder.jpg" alt="" title="" />
<?php } ?>

this should work 这应该工作

$count = 1;
foreach($users as $k => $v) {
?>
    <img src="/images/user_<?php echo $k; ?>.jpg" alt="" title="" />
<?php 
    $count++;
} 

for ($i = $count; $i <= 4; $i++) {
?>
    <img src="/images/user_placeholder.jpg" alt="" title="" />
<?php 
}  
?>
<?php 
$placeholders = array();
foreach($users as $k => $v) {?>
    <img src="/images/user_<?php echo $k; ?>.jpg" alt="" title="" />
    <?php 
    $placeholders[] = '<img src="/images/user_placeholder.jpg" alt="" title="" />';
} 
foreach ($placeholders as $placeholder){
    echo $placeholder;
} ?>

As you can see, there are a dozen ways to skin this particular cat. 如您所见,有十几种方法可以给这只猫皮剥皮。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM