dongsui8162 2017-06-20 11:09
浏览 42
已采纳

每5个项目对数组中的项目进行分组,并在php中添加短划线

I'm building a loop that in my mind will output an array of items divided by a range of 5 numbers. I tried a few function like range, sort, implode, but I haven't found the right solution yet.

So far my code is the following:

foreach (range(0, 100, 5) as $number) {
  echo $number;
  print implode("-", str_split($number));
}

My goal is to output something like:

1-5
5-10
10-15

and so on that I can associate to anything, so essentially a range of numbers every a certain amount of numbers.

Plus I'm not sure if it's the right loop.

I guess I can obtain pretty much the same result with a for loop like:

for($i = 0; $i < 100; $i+=5)
{
     implode("-", str_split($i));
}

Where's my mistake?

UPDATE I probably forget to mention that everything is in a select item:

<select class="drops" name="largesan">
    <option selected value> -- How Many Sandwiches? -- </option><?php
    foreach (range(0, 100, 5) as $numbers)
    {
        $mynumber = $numbers . '-' . $numbers + 5;
        ?>
        <option value="<?php echo $numbers;?>"><?php echo $mynumber;?></option>
        <?php
    }
    ?>
</select>

展开全部

  • 写回答

2条回答 默认 最新

  • doutongxuan1614 2017-06-20 11:13
    关注

    You could use a foreach of this type

      foreach (range(0, 90, 5) as $number) {
        $myStr = $number . '-'. $number + 5 ;
        echo '<option value="'. $myStr .'">'. $myStr.'</option>' ;
    
      }
    

    This is the code you should use ..

    select class="drops" name="largesan"> 
      <option selected value> -- How Many Sandwiches? -- </option>
        <?php 
            foreach (range(0, 90, 5) as $number) { 
    
                  $myStr = $number . '-'. $number + 5 ; 
                  echo '<option value="'.  $myStr. '">'. $myStr .'</option>' ;
            }
    
         ?> 
     </select>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部