开发者

How do I find the 1st and 3rd columns from a 3byX grid

I have the following foreach

foreach( $array as $v )
{
    if( SOME LOGIC HERE ) $class 开发者_Go百科= "first";
    if( SOME LOGIC HERE ) $class2 = "third";
        print '<span class="$class $class2">$v["name"]</span>';
} 

I want to set $class1 to be 'third' for every 1st, 4th, 7th, 10th (3n - 2) and $class2 to be set to 'third' for 3rd, 6th, 9th, 12th


foreach( $array as $k => $v ) 
{ 
    if (($k % 3) == 0) { $class = "first"; }
    elseif(($k % 3) == 2) { $class = "third"; }
    else { $class = "second"; }

    print '<span class="$class $class2">$v["name"]</span>'; 
}  


Use the modulus operator

for ($i=0; $i<count($array); $i++)
    {
    if (($i-1)%3 == 0)
        $class = "first";
    else if ($i % 3 == 0)
        $class = "third";

    echo '<span class="'.$class.'">blablabla</span>
    }


<?php
$n = 0;
foreach( $array as $v ) 
{ 
    $n++;
    switch($n) {
        case 1:
            $class = 'first';
            break;
        case 3:
            $class = 'third';
            $n = 0;
            break;
        default:
            $class = '';
            break;
    }
    print '<span class="' . $class . '">' . $v['name'] . '</span>'; 
}
?>

Edit: Updated the code, the print should go inside the loop :) and cleaned up the code.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜