简体   繁体   English

停止并继续foreach循环

[英]Stop and continue foreach loop

I've got a page of HTML blocks and they're all the same. 我有一页HTML块,它们都是一样的。 As a result, I'm using a foreach loop to duplicate the content (up to 6 times). 结果,我使用了一个foreach循环来复制内容(最多6次)。 However, in the middle of the page, I need to break out of the loop, do something else, then continue. 但是,在页面中间,我需要跳出循环,做其他事情,然后继续。 It would look like this: 它看起来像这样:

BLOCK 1
BLOCK 2
BLOCK 3

(jump out of loop)

BLOCK 4
BLOCK 5

I've tried using an if statement : 我试过使用if statement

if on `BLOCK 3`: 
insert some content afterwards

But ideally I'd like to stop it, then start it (as the content being inserted is in no way related). 但是理想情况下,我想先停止它,然后再启动它(因为要插入的内容没有任何关系)。

In theory I could do this with two foreach loops (one on each side), but that in my mind, seems unnecessary. 从理论上讲,我可以使用两个foreach循环(每侧一个)来完成此操作,但是在我看来,这似乎是不必要的。

Is there a way to completely jump out of the loop, then return (once some HTML has been written, or a function executed)? 有没有一种方法可以完全跳出循环然后返回(一旦编写了一些HTML或执行了一个函数)?

I'm a novice so any help or advice would be great. 我是新手,所以任何帮助或建议都非常好。

Well do exactly that then: 好吧,那就去做吧:

for (;;) {
    if (needsSpecialThreatment) {
        doSmthSpecial;
        continue;
    }
    doUsualStuff;
}

( continue is a PHP keyword for loops, not pseudocode here) continue是用于循环的PHP关键字,此处不是伪代码)

You're overthinking this. 您想得太多了。 Something like this should do what you need: 这样的事情应该可以满足您的需求:

<?php
    $temp = 0;
    foreach($blocks_of_HTML as $block_of_HTML){
        $temp += 1
        if($temp = 3){
            doSomethingElse();
        }

        //Code to write HTML Block
    }
?>

If all you're needing to do is do something else, just keep track of a counter variable and execute a function to do whatever else you need to do and then allow the loop to continue as expected. 如果您需要做的只是做其他事情,只需跟踪计数器变量并执行一个函数即可完成您需要做的其他事情,然后让循环按预期继续。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM