开发者

Generating a complex unordered list with PHP

I have to display some info in an unordered list like above:

<ul>
  <li class="first">...</li>
  <li>...</li>
  <li class="last">...</li>

  <li class="first">...</li>
  <li>...</li>
  <li class="last">...</li>

  <li class="first">...</li>
  <li>...</li>
  <li class="last">...</li>

  ...
</ul>

I need to print this using PHP.

My question is how can I set that class for the first la last element after each thre开发者_JS百科e results?

Thank you.


As you dump the results, use a counter.

for ($i = 0; $i < $items; $i++){
}

Then, you can MOD the counter to see which element you're on. e.g.:

for ($i = 0; $i < $items; $i++){

  // start with no class applied
  $className = '';

  // 0 / 3 = 0, remainder of 0
  // 3 / 3 = 1, remainder of 0
  // etc.
  if ($i % 3 == 0) $className = 'first';

  // 2 / 3 = 0, remainder of 2
  // 5 / 3 = 1, remainder of 2
  // etc.
  else if ($i % 3 == 2) $className = 'last';

  // print the element, and any class that needs to be applied
  echo '<li class="' . $className . '">...</li>';
}


Something like this...

<ul>
<?
    $classes = array('first', '', 'last');
    for ($i = 0; $i < count($myResults); $i++) :
        $class = $classes[$i % 3];
?>        
<li class="<?=$class?>><?=$myResults[$i]?></li>
<?
    endfor;
?>
</ul>


I am assuming you are using an array:

foreach($array as $index=>$value){
    $class = "";
    if($index%3 == 0){
         $class = "first";
    }
    if($index%2 == 0){
         $class = "last";
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜