如果陣列有一個序列索引,你可以使用一個模運算或按位運算。如果該數組基於非數字或未排序的數字,則需要添加一個計數器。
$i & 1 // odd using bitwise
$i % 2 // odd modulo
那麼,你會得到如下:
$i = 0;
foreach ($rel as $r) { // note that I have used curly brackets. I think it is cleaner more standard
$i++;
$classes = array('related-item');
if ($i % 2 == 0) $classes[] = 'right';
echo '<div class="'.implode(' ', $classes).'"><a href='.get_permalink($r->ID).'>'.'<div class=page-related-title>'.$r->post_title.'</div>'.get_the_post_thumbnail($r->ID, array(50,50)).'</a></div>';
}
或者使用逐:
$i = 0;
foreach ($rel as $r) { // note that I have used curly brackets. I think it is cleaner more standard
$i++;
$classes = array('related-item');
if ($i & 2 == 0) $classes[] = 'right';
echo '<div class="'.implode(' ', $classes).'"><a href='.get_permalink($r->ID).'>'.'<div class=page-related-title>'.$r->post_title.'</div>'.get_the_post_thumbnail($r->ID, array(50,50)).'</a></div>';
}
或者,如果$rel
具有零基於序列索引:
foreach ($rel as $index => $r) { // note that I have used curly brackets. I think it is cleaner more standard
$classes = array('related-item');
if ($index & 2 == 1) $classes[] = 'right';
echo '<div class="'.implode(' ', $classes).'"><a href='.get_permalink($r->ID).'>'.'<div class=page-related-title>'.$r->post_title.'</div>'.get_the_post_thumbnail($r->ID, array(50,50)).'</a></div>';
}
丟棄了代碼並且頁面沒有工作,在Dreamweaver中查看提示它告訴我在此編碼的第四行有一個語法錯誤... – 2012-03-02 09:43:52
以及語法錯誤已得到修復 – 2012-03-02 09:44:37
完美,謝謝 – 2012-03-02 09:48:06