2012-09-03 38 views
1

我有一個循環顯示一次最多12個項目的網格中的項目(3個跨越4個向下)。網格中可以有任意數量的項目(1到12),但是在一行中只有1或2個項目的實例中,我需要將一個類別附加到HTML中。例如:確定項目顯示在網格中的剩餘部分 - PHP

當我有3,6,9,12項 - 沒有要求 當我有4,7,10項(剩餘1項) - 項目4,7和10需要一個類應用 當我有5,8,11項(剩餘2項) - 項目4,5,7,8,10,11需要應用類

我該如何在PHP中執行此操作。每個項目我有以下提供給我:

  • 的頁面
  • 當前項目

道歉的產品總數 - 僞代碼編輯器garbles它:

$howmanyleft = totalproducts - currentproduct 
if ($howmanyleft <= 2) { 
    if ($currentproduct % 3 == 0) { 
     //addclass 
    } 
} 

然後在我的CSS

article.product-single { 
    width: 33.3333%; 
    border-bottom: 1px solid rgb(195,195,195); 
    border-right: 1px solid rgb(195,195,195); 
} 
article.product-single:nth-child(3n) { 
    border-right: none; 
} 

article.lastrow, article.product-single:last-child { 
    border-bottom:none; 
} 

對不起,我有這個錯誤。這不是我需要的。我很抱歉。我只需要用類標記的剩餘項目,而不是每一行。

如果有4項,第4項被舉報 如果有5個項目,項目4和5的get標記 如果有10個項目,10項被舉報 如果有11個項目,項目10和11 GET標記

回答

2

如果我理解正確你的問題,你需要像下面的一些代碼:

// check how many items will remain in the final row (if the row is not filled with 3 items) 
$remainder = $total_items % 3; 
for ($i = 0; $i < $total_items; $i++) { 
    if($remainder > 0 && $i >= $total_items - $remainder) { 
     // executed for items in the last row, if the number of items in that row is less than 3 (not a complete row) 
    } else { 
     // executed for items that are in 3 column rows only 
    } 
} 

下面是一個完整的例子,它是如何工作的。使用以下代碼創建一個新的php文件並查看輸出。

// add some random data to an array 
$data = array('one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven'); 
$total_items = count($data); 

// check how many items will remain in the final row (if the row is not filled with 3 items) 
$remainder = $total_items % 3; 

// loop through all the items 
for ($current_item = 0; $current_item < $total_items; $current_item++) { 
// check to see if the item is one of the items that are in the row that doesn't have 3 items 
    if($remainder > 0 && $current_item >= $total_items - $remainder) { 
     echo $data[$current_item] . " - item in last row, when row is not complete<br />"; 
    // code for regular items - the ones that are in the 
    } else { 
     echo $data[$current_item] . " - item in filled row<br />"; 
    } 
} 
+0

謝謝拉扎爾,這將是理想的項目,但因爲我已經改變通過PHP稍微添加我的類以更簡單的方式。 – Jeepstone

+0

你願意粘貼我們正在談論的代碼的一部分,所以我可以給你一個更合適的答案? –

+0

當然。我會更新這個問題。該代碼是一個JShop網站(www.jshop.co.uk)。 – Jeepstone

0

它只是NUMBER_OF_PRODUCTS模number_of_columns

4 % 3 == 1 
5 % 3 == 2 
6 % 3 == 0 
+0

這是用來結合添加一個「LASTROW」類,其中n-總<2和n%3!= 0 – Jeepstone