0

我正在尝试将我的数组返回到两列。当结果数为偶数但不是奇数时,它正在工作。当结果为奇数时,它将所有结果保留在左侧ul,而不是右侧ul

如何更改代码,以便在有余数时将奇数个结果放入第二列?

<?php 
$terms = get_field('featured_cities');
echo '<ul>';
$i =0;
foreach ($terms as $term) {
  echo '<li><a href="'.get_term_link($term->slug, 'cities').'">'.$term->name.'</a></li>';
  $i++;
  if((int)sizeof($terms)/2 == $i){
     echo '</ul><ul>';
  }
}
echo '</ul>';
?>
4

2 回答 2

0

那是因为如果 的大小$terms是奇数,则您缺少开始<ul>标签。

于 2013-05-28T15:46:20.287 回答
0

利用

if (ceil(count($terms)/2) == $i){

代替

if((int)sizeof($terms)/2 == $i){

另外,考虑放入ceil(sizeof($terms)/2)一些变量,所以

<?php 
$terms = get_field('featured_cities');
echo '<ul>';
$i =0;
$half = ceil(count($terms) / 2);
foreach ($terms as $term) {
  echo '<li><a href="'.get_term_link($term->slug, 'cities').'">'.$term->name.'</a></li>';
  $i++;
  if ($half == $i){
     echo '</ul><ul>';
  }
}
echo '</ul>';
?>

如果您想要第二列中的奇数,请添加以下固定$half

$cnt = count($terms);
$half = ceil($cnt / 2);
if ($cnt % 2 && $half % 2) $half--;
于 2013-05-28T15:51:51.830 回答