2012-10-19 31 views
0

我有一個foreach循環,我需要確定單個項目的位置。這些項目總是9.我使用這個代碼。有人有更優雅的解決方案?確定在foreach循環中的位置

<?php 
    foreach($fruit as $key => $apple); 
?> 
    <li class="<?php if(($key == 0) || ($key == 3) || ($key == 6)) echo 'first'; if(($key == 1) || ($key == 4) || ($key == 7)) echo 'middle'; if(($key == 2) || ($key == 5) || ($key == 8)) echo 'last'; ?>" 
      //stuff 
    </li> 
<?php endforeach; ?> 
+1

3模給你0,1,2開始,中間和結束 –

+0

嗨,託尼,你可以發表一個例子嗎?謝謝。 – Francesco

回答

1

按要求評論雖然PHP是我做的比陶工多一點與

<?php foreach($fruit as $key => $apple); ?> 
     <?php $position = $key % 3; ?>  
    <li class="<?php if($position == 0) echo 'first'; 
        if($position == 1) echo 'middle'; 
        if($position == 2) echo 'last'; ?>" 
      //stuff 
    </li> 
<?php endforeach; ?> 

%一門語言是從整數除法的餘

0/3 = 0 remainder 0 
1/3 = 0 remainder 1 
2/3 = 0 remainder 2 
3/3 = 1 remainder 0 
... 
8/3 = 2 remainder 2 
1

如果需要原來的位置,你應該最有可能被使用for循環而不是foreach。您也可以使用模運算符來擺脫長度邏輯語句。

<?php 
    for($i = 0; $i < count($fruit); $i++) { 
     $apple = $fruit[i]; 
     $remainder = $i % 3 
?> 

    <li class="<?php 
     if($remainder == 0) echo 'first'; 
     if($remainder == 1) echo 'middle'; 
     if($remainder == 2) echo 'last'; ?>" 

    // stuff 

    </li> 

<?php } ?> 
+0

$ fruit.length? –