dtf54486 2012-04-26 14:50
浏览 34
已采纳

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

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)

  • 写回答

4条回答 默认 最新

  • douzi2749 2012-04-26 14:53
    关注

    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. :)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥20 Java-Oj-桌布的计算
  • ¥15 请问如何在openpcdet上对KITTI数据集的测试集进行结果评估?
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路