【问题标题】:Using a conditional inside of a PHP foreach loop在 PHP foreach 循环中使用条件
【发布时间】:2012-08-25 18:08:08
【问题描述】:

我正在使用这样的 php foreach 语句:

<?php foreach($files as $f): ?>

大量的 HTML

<?php endforeach; ?>

我怎样才能在循环中放置一个条件,以便它可以跳到下一次迭代。我知道我应该使用 continue,但我不确定如何使用这样的封闭 php 语句来做到这一点。它会是一个单独的php语句吗?是否可以将其放置在 HTML 的中途,以便执行循环中的部分但不是全部内容?

【问题讨论】:

  • 好吧,介于两者之间。在您需要的地方。
  • 你能澄清你的问题吗?还有一些代码?

标签: php html


【解决方案1】:

是的,您可以在任意位置插入条件和continue

<?php foreach($files as $f): ?>

lots of HTML

<?php if (condition) continue; ?>

more HTML

<?php endforeach; ?>

See it in action.

【讨论】:

    【解决方案2】:

    我遇到了一个非常相似的问题,所有搜索都把我带到了这里。希望有人发现我的帖子有用。从我自己的代码: 对于 PHP 5.3.0 这有效:

    foreach ($aMainArr as $aCurrentEntry) {
        $nextElm = current($aMainArr); //the 'current' element is already one element ahead of the already fetched but this happens just one time!
        if ($nextElm) {
            $nextRef = $nextElm['the_appropriate_key'];
            next($aMainArr); //then you MUST continue using next, otherwise you stick!
        } else { //caters for the last element
        further code here...
        }
    //further code here which processes $aMainArr one entry at a time...
    }
    

    对于 PHP 7.0.19,以下工作:

    reset($aMainArr);
    foreach ($aMainArr as $aCurrentEntry) {
        $nextElm = next($aMainArr);
        if ($nextElm) {
            $nextRef = $nextElm['the_appropriate_key'];
        } else { //caters for the last element
        further code here...
        }
    //further code here which processes $aMainArr one entry at a time...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-27
      • 2016-06-05
      • 1970-01-01
      • 1970-01-01
      • 2010-11-16
      • 1970-01-01
      • 2014-10-19
      • 1970-01-01
      相关资源
      最近更新 更多