php foreach循环问题


php foreach loop issue

我有这个函数来生成动态html菜单我的问题是,每次循环计数超过5个我想知道如果数字超过5,ul标签只出现一次该怎么办

     function GenerateNavHTML($rows ,$count=5)
    {
        $html = '';
        $html .= '<div>';
        foreach($rows as $key =>$value)
        {
            if(count($rows) > $count)
            {
                 $html .= '<ul>';
                 $html .='<li>';
                 $html .= '<a href="' . $value['title'] . '">' . $value['title'] . '</a>';
                 $html .= '</li>';
                 $html .= '</ul>';
            }
            else
            {
                 $html .='<li>';
                 $html .= '<a href="' . $value['title'] . '">' . $value['title'] . '</a>';
                 $html .= '</li>';
            }

        }
        $html .= '</div>';
        return $html;
    }
    this the structure of html code 
                           <div>
                                   <ul>
                                        <li><a href="#"> 1</a></li>
                                    </ul>
                                    <ul>
                                        <li><a href="#"> 1</a></li>
                                    </ul>
                                </div>

只需在每个外部重新定位UL

function GenerateNavHTML($rows ,$count=5)
{
    $html = '';
    $html .= '<div><ul>';
    $ctr = 0;
    foreach($rows as $key =>$value)
    { 
        if(!$ctr)
             $html .= "<ul>";
        $html .='<li>';
        $html .= '<a href="' . $value['title'] . '">' . $value['title'] . '</a>';
        $html .= '</li>';              
        $ctr++;
        if($ctr == $count)
        {
            $html .= "</ul>";
            $ctr = 0;
        }

    }
    if($ctr > $count)
     $html .= '</ul>';
    $html .= '</div>';
    return $html;
}

如果我正确理解你,这应该可以做到:

foreach($rows as $key =>$value){
    if(count($rows) > $count){
        $html .= '<ul>';
    }
    $html .='<li>';
    $html .= '<a href="' . $value['title'] . '">' . $value['title'] . '</a>';
    $html .= '</li>';
    if(count($rows) > $count){
        $html .= '</ul>';
    }
}

只需将不想重复的部分移动到foreach循环之外,即

function GenerateNavHTML($rows ,$count=5)
{
    $html .= '<div><ul>';
    ...

而在循环中,您可以从<li>...</li> 开始