PHP,在动态循环周围添加div环绕

时间:2018-10-20 01:09:45

标签: php

我正在处理日历脚本,以输出按月分组的事件。一切工作正常,除非我不知道如何在每个月左右添加div包装器而没有一些结束标记问题。这是我的循环代码:

if ($posts) {

    $month_titles = array();
    $close = false;  

    foreach( $posts as $post ) {
      setup_postdata( $post ); 
      $month_title = date('F Y', strtotime(get_post_meta($post->ID,'_event_start_local', true)));

      if(!in_array($month_title, $month_titles)) {
        if($close) echo '</ul>';                                                             
        echo '<h4>'.$month_title.'</h4>';
        echo '<ul>';                         
        $month_titles[] = $month_title;                                                         
        $close = true;  
      }
      echo '<li>'.get_the_title().'</li>';

    }
    if ($close) echo '</ul>';
}

这是当前的输出方式:

<h4>Month Name 2018</ul>
<ul>
  <li>Title of Event</li>
  <li>Title of Event</li>
</ul>

我希望它像这样:

<div>
  <h4>Month Name 2018</h4>
  <ul>
    <li>Title of Event</li>
    <li>Title of Event</li>
  </ul>
</div>

我尝试了几种添加div换行的方法,它关闭得太早或太晚。我需要对此重新审视,因为我已经把它弄得太久了!

2 个答案:

答案 0 :(得分:1)

此逻辑应可满足您的需求:

// preset some vars
$oldMonth = null;
$firstItem = true; 

foreach($posts as $post) {
  setup_postdata($post); 
  $month_title = date('F Y', strtotime(get_post_meta($post->ID,'_event_start_local', true)));

  // check if we have a new month coming up:
  if($oldMonth != $month_title) {
    // when it's the first one ever, just open the div     
    if($firstItem) {
       echo "<div>";
       $firstItem = false;  //..and remember that the following aren't the first
    } else {  // else close the previous ones and open a new one
       echo "</ul></div><div>";
    }
    // show the new month and open the list
    echo '<h4>'.$month_title.'</h4>';
    echo '<ul>';                         
  }
  echo '<li>'.get_the_title().'</li>';
  $oldMonth = $month_title;  // remember the last month

}
// at the end close the last ul and last div
echo '</ul></div>';

答案 1 :(得分:1)

似乎只是更改了这些行:

if($close) echo '</ul>';                                                             
echo '<h4>'.$month_title.'</h4>';

if($close) echo '</ul></div>';                                                             
echo '<div><h4>'.$month_title.'</h4>';

应该做你想要的。请注意,您必须在代码的两个地方都更改$close上的if)