duanlanzhi5509 2013-04-03 23:06
浏览 33
已采纳

首先需要ul有1 li,每个ul有5 li

I need this type of structure in PHP foreach loop. and i tried this code :

<ul>
    <li>1</li>
</ul>
<ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
</ul>
<ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
</ul>
<ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
</ul>

i tried this condition inside loop and working fine but i need 1 li on first ul.

<?php
$counter = 1;
foreach( $myposts as $post ) :

  setup_postdata($post); 

  if ($counter % 5 == 1) {
    echo '<ul>';
  }
  echo '<li>testing ...</li>'

  if($counter % 5 == 0) {
    echo '</ul>';
  }
  $counter++;
endforeach;
?>

any one extend my logic ??

  • 写回答

1条回答 默认 最新

  • drf65218 2013-04-03 23:20
    关注

    This is what I came up with:

    $myposts = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16);
    
    $counter = 0;
    echo '<ul>';
    foreach( $myposts as $k=>$post ) :
        //setup_postdata($post); 
        echo '<li>'.$post.'</li>';
        if($counter==0 || $counter==5){
            echo "</ul>".($k!=count($myposts)-1 ? "<ul>" : "");
            $counter = 0;
        }
        $counter++;
    endforeach;
    if($counter==5){
        echo '</ul>';
    }
    

    This largest misconception most people don't bother to close that last tag (in your case ul), or they open a new tag (in your case ul) when they shouldn't.

    P.s. I had to comment setup_postdata for this to work.

    Note: Adding or removing elements from the array will not effect the structure of 1,5,5,...,(then remainder depending on what is left)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制