php foreach循环问题

时间:2013-11-26 07:48:30

标签: php html foreach

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

     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>

3 个答案:

答案 0 :(得分:1)

只需将你的UL重新定位在foreach之外

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;
}

答案 1 :(得分:0)

如果我理解正确,应该这样做:

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>';
    }
}

答案 2 :(得分:0)

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

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

在循环内部,您从<li>...</li>

开始
相关问题