【问题标题】:foreach loop where is the place of the closing ul?foreach 循环结束 ul 的位置在哪里?
【发布时间】:2015-09-14 23:52:55
【问题描述】:

我想显示所有现有类别和所有帖子。

我写了一个foreach循环,但是不知道结束ul标签的位置在哪里。

我的代码:

<?php
 $current_cat = 0;
 $curr_nb_item = 0;
 foreach($blog_widget as $row)
   {
   if($current_cat != $row->category_id)
    {   
    $current_cat = $row->category_id;
    echo "<ul>     " . $row->category_id . " ";    
    echo "<li>";
    echo $row->title;
    echo "</li>";
    ++$curr_nb_item;            
   }
    else { 
        echo "<li>";
        echo $row->title;
        echo "</li>";
        ++$curr_nb_item;    
    }
}
?>

现在我在 html 中得到了这个结果:

<ul>1
<li>
cat 1 post n
</li>
<li>
cat 1 post h
</li>

<ul>2
<li>
cat 2 post x
</li>
<li>
cat 2 post y
</li>

我尝试了很多变化但没有结果。我希望有人可以帮助我。非常感谢。

【问题讨论】:

  • 我相信最后两个之间}:} echo '&lt;/ul&gt;'; }
  • 不是,我已经试过了。

标签: php list loops foreach


【解决方案1】:

这可能不是最干净的,但应该可以。修改 if 语句的顶部,如下所示:

if($current_cat != $row->category_id)
{
    if ($row != $blog_widget[0])
    {
        echo "</ul>";
    }

    $current_cat = $row->category_id;
    echo "<ul>     " . $row->category_id . " ";

    // etc...

然后在你的 foreach 循环的右大括号之后:

echo "</ul>";

【讨论】:

    猜你喜欢
    • 2018-02-12
    • 1970-01-01
    • 2013-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多