5

我正在尝试使用 foreach 语句来显示列表 ul>li。如果列表没有元素,我该如何处理该标准。

    <ul>
    <?php foreach($person['CastsMovie'] as $cast): ?>
      <li><?php echo $this->Html->link($cast['Movie']['name'], array('controller' => 'movies', 'action' => 'view', $cast['movie_id'],  'admin' => true), array('escape' => false)); ?> (<?php echo date("Y", strtotime($cast['Movie']['MovieDetail']['release_date'])); ?>)</li>
      <?php endforeach; ?>
    </ul>
4

3 回答 3

6

检查是否为

if ( !empty( $person ) ) {
  foreach ( $person as $cast ) {
    echo "<li>$cast</li>";
  }
} else {
  echo "<li>This play has no cast members.</li>";
}
于 2012-04-29T05:48:45.027 回答
1

实际上,您需要用支票包围 UL。否则你会得到一个不必要的空“ul”标签:

<?php if (!empty($person['CastsMovie'])) { ?>
<ul>
<?php foreach($person['CastsMovie'] as $cast) { ?>
  <li><?php echo $this->Html->link($cast['Movie']['name'], array('controller' => 'movies', 'action' => 'view', $cast['movie_id'],  'admin' => true), array('escape' => false)); ?> (<?php echo date("Y", strtotime($cast['Movie']['MovieDetail']['release_date'])); ?>)</li>
  <?php } ?>
</ul>
<?php } ?>

这意味着:您检查是否有任何列表元素(在您的情况下将此人 CastsMovies),如果有,则显示列表(ul + li)。如果不是,完整的列表将被省略(不仅仅是子 li 元素)。

于 2012-04-29T09:58:20.143 回答
0

首先,在您使用的任何“控制器”中,准备您的数据,使其适合模板。

foreach($person['CastsMovie'] as $key => $cast) {
  $cast['html_link'] = $this->Html->link($cast['Movie']['name'], 
                                         array('controller' => 'movies', 
                                               'action' => 'view', 
                                               $cast['movie_id'], 
                                               'admin' => true), 
                                         array('escape' => false)
                               ); 
  $cast['html_date'] = date("Y", strtotime($cast['Movie']['MovieDetail']['release_date']));
  $person['CastsMovie'][$key] = $cast;
}

然后使您的模板清晰易读

<?php if($person['CastsMovie']: ?>
<ul>
<?php     foreach($person['CastsMovie'] as $cast): ?>
  <li>
    <?=$cast['html_link']?> (<?=$cast['html_date']?>)
  </li>
<?php     endforeach ?>
</ul>
<?php endif ?>
于 2012-04-29T10:17:58.013 回答