【问题标题】:How to add "else" to "foreach"?如何在“foreach”中添加“else”?
【发布时间】:2017-07-14 22:34:58
【问题描述】:

我不知道如何将else 添加到foreach

这是我的代码:

<?php $terms = get_the_terms( $post->ID , 'actor' ); 
    foreach ( $terms as $term ) {
        $term_link = get_term_link( $term, 'actor' );
        if( is_wp_error( $term_link ) )
        continue;
        echo '<a href="' . $term_link . '">' . $term->name . '</a>';
    }
?>

【问题讨论】:

  • 到目前为止,您真的尝试过什么吗?顺便说一句:foreach 不支持else,但if 支持。
  • 你想在逻辑上实现什么......?
  • @FranzGleichmann - 有趣的是,我最近看到一些建议为foreach 提出了else
  • @MarkBaker 我最近看到了类似的东西,我相信它是 twig 的一部分,这不是一个坏主意 - 但到目前为止,大多数语言(包括 PHP)都没有实现任何东西喜欢。

标签: php wordpress foreach


【解决方案1】:

您可以尝试类似的方法:

<?php 
    $terms = get_the_terms( $post->ID , 'actor' ); 
    if ($terms) {
        foreach ( $terms as $term ) {
            $term_link = get_term_link( $term, 'actor' );
            if ( is_wp_error( $term_link ) )
                continue;
            echo '<a href="' . $term_link . '">' . $term->name . '</a>';
        }   
    } else {
        // do the work for else
    }
?>

【讨论】:

    【解决方案2】:

    foreach 是一个循环。 else 是条件语句的一部分。看起来您只想在循环中添加一个条件。这只是一个标准条件。

    if ($a > $b) {
      echo "a is greater than b";
    } else {
      echo "a is NOT greater than b";
    }
    

    在这种情况下,我假设您想break 循环。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-08
      • 1970-01-01
      • 1970-01-01
      • 2018-04-24
      • 2018-10-26
      • 1970-01-01
      • 2017-01-21
      • 2011-09-26
      相关资源
      最近更新 更多