dongtan7418 2013-12-22 19:32
浏览 247
已采纳

PHP循环:从第2个开始每4次迭代

I have an array that can have any number of items inside it, and I need to grab the values from them at a certain pattern.

It's quite hard to explain my exact problem, but here is the kind of pattern I need to grab the values:

  1. No
  2. Yes
  3. No
  4. No
  5. No
  6. Yes
  7. No
  8. No
  9. No
  10. Yes
  11. No
  12. No

I have the following foreach() loop which is similar to what I need:

$count = 1;

foreach($_POST['input_7'] as $val) {        
if ($count % 2 == 0) {
        echo $val;
        echo '<br>';
    }

    $count ++;
}

However, this will only pick up on the array items that are 'even', not in the kind of pattern that I need exactly.

Is it possible for me to amend my loop to match that what I need?

  • 写回答

2条回答 默认 最新

  • duanquan1876 2013-12-22 19:40
    关注

    You can do this much simpler with a for loop where you set the start to 1 (the second value) and add 4 after each iteration:

    for ($i = 1; $i < count($_POST['input_7']); $i += 4) {
        echo $_POST['input_7'][$i] . '<br />';
    }
    

    Example:

    <?php
        $array = array(
            'foo1', 'foo2', 'foo3', 'foo4', 'foo5', 
            'foo6', 'foo7', 'foo8', 'foo9', 'foo10', 
            'foo11', 'foo12', 'foo13', 'foo14', 'foo15'
        );
    
        for ($i = 1; $i < count($array); $i += 4) {
            echo $array[$i] . '<br />';
        }
    ?>
    

    Output:

    foo2
    foo6
    foo10
    foo14

    DEMO

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

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?