数组中的if语句

时间:2019-07-16 11:06:29

标签: php arrays wordpress if-statement

我正在使用以下循环显示特定类别中的事件:

<?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语句在数组中不起作用。正确的方法是什么?

1 个答案:

答案 0 :(得分: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'),
)