1

一度に最大 12 個のアイテムのグリッドにアイテムを表示するループがあります (横に 3 つ、下に 4 行)。グリッドには任意の数 (1 ~ 12) の項目を含めることができますが、1 行に 1 つまたは 2 つの項目しかない場合は、HTML にクラスを追加する必要があります。例えば:

アイテムが 3、6、9、12 個ある場合 - 何も必要ありません アイテムが 4、7、10 個ある場合 (残り 1 個) - アイテム 4、7、および 10 は適用するクラスが必要です アイテムが 5、8、11 個ある場合 (残り 2 個) ) - 項目 4、5、7、8、10、11 には適用するクラスが必要です

PHPでこれを行うにはどうすればよいですか。各アイテムについて、次のものを用意しています。

  • ページ上の商品の総数
  • 現在のアイテム

お詫び - 編集者が文字化けした疑似コード:

$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 にフラグが付けられます アイテムが 10 個の場合、アイテム 10 にフラグが付けられます アイテムが 11 個の場合、アイテム 10 と 11 にフラグが付けられます

4

2 に答える 2

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 />";
    }
}
于 2012-09-03T12:49:03.500 に答える
0

number_of_products modulo number_of_columns です。

4 % 3 == 1
5 % 3 == 2
6 % 3 == 0
于 2012-09-03T12:39:15.870 に答える