doutui6241 2016-09-11 19:32
浏览 23
已采纳

具有空白列表条目的Foreach范围

Let's say I have an external source I'm gathering data from and putting it into list form. This external source can have anywhere from 1 - 100 entries. Let's use rand() and range() to represent this. (a minimum of 1, and a random number between 1 and 15 as our total 'entries')

<?php
$max = rand(1, 15);
$range = range(1, $max);
?>
       <ul> 
<?php
foreach ($range as $number) {
echo '<li>' . $number . '</li>';
}
?>
      </ul>

This echo's out like this:

  • 1
  • 2
  • 3
  • 4

Now let's say I want <li> to always echo out a total of 10 times.

Even if my list ($number) is as low as 1, or as high as 15.

If it's 1, it displays the first entry, and then 9 blank <li></li> (actually, in my code it won't be blank, but will have my own specified text inside. Such as <li>Blank Entry</li>

If it's 15, it displays the first 10 entries, and cuts off the last 5.

I get how I could set the range in my foreach to stop after 10 iterations in the latter example, but how do I account for the blank <li> listings in the former?

  • 写回答

1条回答 默认 最新

  • dousi2029 2016-09-11 19:58
    关注

    Not sure why this was dinged...just create another array and fill that array with your random values. The other array accepts those values, up to 10, and if the original array has less than 10 values, it populates it with 'blank'.

    <?php
        $max = rand(1, 15);
        $range = range(1, $max);
        $arr = [];
    
        for($i=0; $i<=9; $i++){
          if(isset($range[$i])){
            $arr[] = $range[$i];
          }else{
            $arr[] = 'blank';
          }
        }
        ?>
        <ul>
        <?php
        foreach ($arr as $number) {
          echo '<li>' . $number . '</li>';
        }
        ?>
        </ul>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教