【问题标题】:If statement within array [duplicate]数组中的 if 语句 [重复]
【发布时间】:2019-07-16 11:06:29
【问题描述】:

我正在使用以下循环来显示某个类别中的事件:

<?php

  global $post;

  $junior = tribe_get_events(
    array(
      'tax_query'=> array(
        array(
          'taxonomy' => 'tribe_events_cat',
          'field' => 'slug',
          'terms' => 'junior'
        )
      )
    )
  );

  $senior = tribe_get_events(
    array(
      'tax_query'=> array(
        array(
          'taxonomy' => 'tribe_events_cat',
          'field' => 'slug',
          'terms' => 'senior'
        )
      )
    )
  );

  $sixth = tribe_get_events(
    array(
      'tax_query'=> array(
        array(
          'taxonomy' => 'tribe_events_cat',
          'field' => 'slug',
          'terms' => 'sixth'
        )
      )
    )
  );

  foreach ( $junior as $post ) {
    setup_postdata( $post );
    echo ' <a href=" ' .get_permalink().' ">'.tribe_get_start_date( $post,'l j F Y' ).'</a>';
  }

  foreach ( $senior as $post ) {
    setup_postdata( $post );
    echo ' <a href=" ' .get_permalink().' ">'.tribe_get_start_date( $post,'l j F Y' ).'</a>';
  }


  foreach ( $sixth as $post ) {
    setup_postdata( $post );
    echo ' <a href=" ' .get_permalink().' ">'.tribe_get_start_date( $post,'l j F Y' ).'</a>';
  }
?>

如您所见,我在这里重复了很多代码。对于每个数组,唯一变化的数据位是“术语”。

我尝试在数组中使用 if 语句,如下所示:

<?php

  global $post;

  $category_array = tribe_get_events(
    array(
      'tax_query'=> array(
        array(
          'taxonomy' => 'tribe_events_cat',
          'field' => 'slug',
          'terms' => if ($junior) { echo 'junior'; }
        )
      )
    )
  );

  // Retrieve posts from Junior School Open Day category
  $junior = $category_array;

我从那以后读到 if 语句在数组中不起作用。这样做的正确方法是什么?

【问题讨论】:

  • 使用三元语句。

标签: php arrays wordpress if-statement


【解决方案1】:

内联可以使用三元运算符:

array(
  'taxonomy' => 'tribe_events_cat',
  'field' => 'slug',
  'terms' => $junior ? 'junior-school-open-day' : 'other-value',
)

可以嵌套:

array(
  'taxonomy' => 'tribe_events_cat',
  'field' => 'slug',
  'terms' => $junior ? 'junior-school-open-day' : ( $senior ? 'second-value' : 'third-value'),
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-16
    相关资源
    最近更新 更多