是否可以关闭</ul>并在循环中添加新的<ul>?

时间:2019-11-24 19:04:55

标签: php jquery html css html-lists

我正在显示数据库中的数据。目前,我的数据库中有6条记录,并且得到类似

的输出
<ul>
<li>Records1</li>
<li>Records2</li>
<li>Records3</li>
<li>Records4</li>
<li>Records5</li>
<li>Records6</li>
</ul>

现在我正在做的是,我必须在第4个</ul>标签之后关闭li标签,然后在第4个ul之后启动新的li

我的预期输出是

<ul>
<li>Records1</li>
<li>Records2</li>
<li>Records3</li>
<li>Records4</li>
</ul>

<ul>
<li>Records5</li>
<li>Records6</li>
</ul>

有可能吗?

我正在使用以下代码

<?php 
    if ($tyler_query->have_posts()) {
                $index = 0;
                $check=0;
                $first4=0;

      while ( $tyler_query->have_posts() ) {
              $tyler_query->the_post();

           if ($index < 4) {
                     if ($first4==0){?>
<ul>
  <?php $first4=1;}?>
  <li>
    <!--output here-->
  </li>
  <?php  if ($first4==4){?>
</ul>
<?php }?>

<?php } 
            else {
                if ($check==0){?>
<ul>
  <?php $check=1;}?>
  <li>
    <!--output here-->
  </li>
  <?php  }  $index++;}?>
</ul>

<?php   }?>

3 个答案:

答案 0 :(得分:0)

只要符合您的条件,您只需在其后插入一个结束标签即可。在下面的每三个项目之后:

<?php

$items = [
    'Syd',
    'Roger',
    'Nick',
    'David',
    'Richard'
];

$i = 0;
echo '<ul>';
foreach($items as $item) {
    if($i++%3 == 0)
        echo '</ul><ul>';
    echo '<li>' . $item . '</li>';
}
echo '</ul>';

输出:

<ul><li>Syd</li><li>Roger</li><li>Nick</li></ul><ul><li>David</li><li>Richard</li></ul>

答案 1 :(得分:0)

这是一个简单的例子。希望能帮到您。

if ($tyler_query->have_posts()) {

    $index = 0;
    $check = 6;
    ?>

    <ul>
    <?php while ($tyler_query->have_posts()) {

        $tyler_query->the_post(); ?>

        <li><?php echo 'some_value' ?></li>

        <?php if ($index % $check === 0 ) { ?>

        </ul><ul>

        <?php }

        $index++;
    } ?>
    </ul>

<?php } ?>

答案 2 :(得分:-1)

如果您在浏览器中回显要查看的HTML标记/输出,您的代码将起作用。

<?php
if ($tyler_query->have_posts()) {
    $index = 0;
    $check = 0;
    $first4 = 0;

    while ($tyler_query->have_posts()) {

        $tyler_query->the_post();
        $output = "whatever the output object is";

        if ($index < 4) {
            if ($first4 == 0) {
                echo '<ul>';
                $first4 = 1; // increment so that the this if block wont trigger again
            }
            echo '<li>' . $output . '</li>';
            // increment so that the next if block trigger once
            if ($first4 == 4) {
                echo  '</ul>';
            }
            $first4++;
        }
        if ($index >= 4){
            if ($check == 0) {
                echo '<ul>';
                $check = 1;
            }
            // assuming you want to have the rest of the data in this block.
            // data 5 and above
            else {
                echo '<li>' . $output . '</li>';
            }
        }
            $index++;
        }
    echo '</ul>';
    } 
?>