if else 语句来标识数组中的最后一个项



我有以下代码来列出terms数组,如果有多个term分配给帖子,我会在术语之间放置一个逗号。

$terms = get_terms('my_term', $args);
if (!empty($terms) && !is_wp_error($terms)) {
    $count = count($terms);
    $i = 0;
    $term_list = '<span>';
    foreach ($terms as $term) {
        $i++;
        $term_list .= '#<a href="' . esc_url(get_term_link($term)) . '"><span>' . $term->name . '</span></a>';
        if ($count != $i) {
            $term_list .= ', ';
        } else {
            $term_list .= '</span>';
        }
    }
}

现在,我想在最后两个任期之间放置一个&,而不是,如果有多个任期分配给该职位。

我认为用数组解决它更容易。

$terms = get_terms('my_term', $args);
if (!empty($terms) && !is_wp_error($terms)) {
    $term_array = [];
    foreach ($terms as $term) {
        $term_array[] = '#<a href="' . esc_url(get_term_link($term)) . '"><span>' . $term->name . '</span></a>';
    }
    if(count($term_array) > 1){
        $last = array_pop($term_array);
        $term_list = '<span>' . implode(', ', $term_array) . '</span>';
        $term_list .= ' & ' . $last;
    } else {
        $term_list = '<span>' . $term_array[0] . '</span>';
    }
}

或:

$terms = get_terms('my_term', $args);
if (!empty($terms) && !is_wp_error($terms)) {
    $count = count($terms);
    $i = 1;
    $term_list = '<span>';
    foreach ($terms as $term) {
        $term_list .= '#<a href="' . esc_url(get_term_link($term)) . '"><span>' . $term->name . '</span></a>';
        if($i !== $count){
            if($i === $count - 1){
                $term_list .= ' & ';
            } else {
                $term_list .= ', ';
            }
        }
        $i++;
    }
    $term_list .= '</span>';
}

检查$count是否等于$i + 1

if ($count != $i) {
    if ($count == $i + 1)
       $term_list .= '& ';
    else
       $term_list .= ', ';
} else {
    $term_list .= '</span>';
}

这应该可以做到。

您可以检查$count是否等于$i

$i = 1;
if ($count != $i) {
    $term_list .= ', ';
} else if ($count == $i) {
    $term_list .= '& ';
} else {
    $term_list .= '</span>';
}

找到数组的最后一个元素,然后根据 lastelement 检查循环中的每个项目,然后执行"魔术";)。 例:

$array = array('a' => 1,'b' => 2,'c' => 3);
$lastElement = end($array);
foreach($array as $k => $v) {
  echo $v . '<br/>';
  if($v == $lastElement) {
     // 'Now you know that $v is the last element, do something'; 
}

}

最新更新