twan twan - 7 months ago 6
HTML Question

Split menu list in two every 7 items

I got a dynamic menu that uses bootstrap, but one menu button has about 14 child items. Way too long for a website, so I want to split it in half.

This is the code that I'm trying to replicate:

<ul class="dropdown-menu dropdown-menu-large row" role="menu">
<li class="col-sm-6">
<ul>
<li><a href="life-insurance.html">Life Insurance</a></li>
<li><a href="life-insurance.html">Home Insurance</a></li>
<li><a href="life-insurance.html">Travel Insurance</a></li>
<li><a href="life-insurance.html">Pet Insurance</a></li>
</ul>
</li>

<li class="col-sm-6">
<ul>
<li><a href="life-insurance.html">Boat Insurance</a></li>
<li><a href="life-insurance.html">Auto Insurance</a></li>
<li><a href="life-insurance.html">Bike Insurance</a></li>
<li><a href="life-insurance.html">Business Insurance</a></li>
</ul>
</li>
</ul>


This is what I tried:

$tel = 1;

foreach ( $nmenuccr as $cmenu ) {

// If id matches and category id is 11 (services) split in half
if ( $cmenu['id'] && $cmenu['catid'] == '11' ){

if($tel == 1) {
$hmenu .= '<li class="col-sm-6"><ul>';
}


$hmenu.= '
<li><a href="'.$cmenu['alias'].'.html">'.$cmenu['title'].'</a></li>
';

if(($tel % 7) == 0){
$hmenu .= '</ul></li> <li class="col-sm-6"><ul>';
}
$tel++;


if(($tel % 7) != 0){
$menu .= '</li>';
}
//Else use the normal dropdown layout
}else{

if (strlen($cmenu['title']) > 25){
$shortstrmen = substr($cmenu['title'], 0, 25) . '...';

$hmenu.= '
<li><a href="'.$cmenu['alias'].'.html">'.$shortstrmen.'</a>
';
}else{
$hmenu.= '
<li><a href="'.$cmenu['alias'].'.html">'.$cmenu['title'].'</a>
';
}

}

}


However this returns the following code:

https://jsfiddle.net/sms16v44/

Does anyone see what I am doing wrong?

Answer

Keepin it a junky piece of code, you can just quick-fix it this way:

$tel = 0;

/* .. */

// If id matches and category id is 11 (services) split in half
if ( $cmenu['id'] && $cmenu['catid'] == '11' ){

    if(++$tel == 1) {
        $hmenu .= '<li class="col-sm-6"><ul>';  
    }


    $hmenu.= '<li><a href="'.$cmenu['alias'].'.html">'.$cmenu['title'].'</a></li>';

    if(($tel % 7) == 0){
        if ($tel == 7) {
            $hmenu .= '</ul></li><li class="col-sm-6"><ul>'; 
        } else {
            $hmenu .= '</ul></li>';
        }
    }
//Else use the normal dropdown layout
} // ..

Working example (updated): http://sandbox.onlinephpfunctions.com/code/13fd6974cd66c847747f44a4be9b892aa47e4979

But you should refactor your $nmenuccr through a function, which will make it an array reflecting the target structure of menu to KISS the view-generating part of code.

Edit: updated operations on $tel.

Comments