cj333
cj333

Reputation: 2609

php set a menu from an array for loop display

$array=array('menu1','menu2','menu3','menu4','menu5','menu6','menu7','menu8','menu9','menu10');

I storied some menu names into an array, Then output some like

enter image description here

in diffirent page, the menu always show 5 items and current page is always 2nd.

enter image description here

And if the current page is in this case, it will loop display menu1, menu2, menu3 after menu10.

foreach($array as $k=>$r){
    if($r==$current){
        $n=$k;//count current memu position
    }
}
echo '<ul>';
foreach($d as $k=>$r){
    if($n>1&&$n<7){//normal situation like first image
        if($k==($n-1)){
            echo '<li><a>'.$r.'</a></li>';
        }else if($k==$n){
            echo '<li class="current">'.$r.'</li>';
        }else{
            echo '<li><a>'.$r.'</a></li>';
        }
    }else{
        //How to do in the case of the second image?
    }
}
echo '</ul>';

Upvotes: 0

Views: 63

Answers (2)

David Lin
David Lin

Reputation: 13353

I think you would also like the menu look like this when the current selection is menu1:

menu10
menu1 [selected]
menu2
menu3
menu4

Here is the algorithm. It looks confusing but I am sure you can figure it out.

$array=array('menu1','menu2','menu3','menu4','menu5','menu6',
               'menu7','menu8','menu9','menu10');

$current = 'menu1';


$startIndex = array_search($current, $array)-1;
$total = count($array);
$result = array();

for($index = $startIndex ; $index <$startIndex+5; $index++){

    $result[] = $array[($index+$total)%$total];  //using % operator

}


print_r($result);

Upvotes: 1

MaxLascombe
MaxLascombe

Reputation: 96

Try this:

if($k==($n-1)){
    echo '<li><a>'.$r.'</a></li>';
}else if($k==$n){
    echo '<li class="current">'.$r.'</li>';
}else{
    if($k >= count($d)-1)
        echo ''<li><a>'.$d[$k-count($d)+1].'</a></li>';
    else
        echo ''<li><a>'.$r.'</a></li>';
}

This actually should work for both cases, so you can remove the big if statement and put this as the body of your foreach.

Upvotes: 0

Related Questions