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 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置