0

假设您有一个包含 30 个字符的数组,并且您正在循环它们以在 HTML 中构建一个可视网格。我想知道它何时在最后一行项目上并应用 CSS 规则。对于每 8 个项目,我可以使用下面的代码应用附加的 CSS 规则:

$cnt=1;
foreach ($characters as $index => $character){
   if ($cnt % 8==0) echo "newline";
   $cnt++;
}

由于我只有 30 个字符,因此将有 3 行和较短的第 4 行(它将只有 6 个项目)。如何将 24-30 之间的每个字符标记为属于最后一行。字符的总数总是不同的。

4

4 回答 4

2
$rowCount = 8; // the number of items per row
$lastRowStarts = intval(floor(count($characters) / $rowCount)) * $rowCount;
// e.g: floor(30 / 8) * 8 = 3 * 8 = 24 = <index of first item in last row>

$index = 1;
foreach ($characters as $character) {
   if ($index >= $lastRowStarts) echo "last line";

   $index++;
}
于 2012-11-12T20:58:50.233 回答
0
$cnt=1;
$length = strlen($characters);//if a string
//$length = count($characters);//if an array
foreach ($characters as $index => $character){
   if ($cnt % 8==0) echo "newline";
   if($index > ($length - 8))//or whatever number you want
   {
      echo 'flagged';//flag here however
   }
   $cnt++;
}
于 2012-11-12T20:59:21.887 回答
0

只要您的行长度为 8,这将适用于任何大小的字符。这假设$cnt是一个保持循环计数器的变量。

$count = count($charchters)

foreach ($characters as $index => $character){
   if ($cnt % 8==0) echo "newline";
   if ($cnt < $count && $cnt > ($count - $count % 8)) echo "This is on the last row";
}
于 2012-11-12T21:00:14.127 回答
0

您可以array_pop在摸索它们后使用它们来获取最后一行array_chunk

header("Content-Type: text/plain");

$characters = range(1, 30); // Generate Random Data
$others = array_chunk($characters, 8); //Break Them apart
$last = array_pop($others); //Get last row

foreach ( $others as $characters ) {
    echo implode("\t", $characters), PHP_EOL;
}

print_r($last); // Do anything you want with last row

输出

1   2   3   4   5   6   7   8
9   10  11  12  13  14  15  16
17  18  19  20  21  22  23  24

最后一排

Array
(
    [0] => 25
    [1] => 26
    [2] => 27
    [3] => 28
    [4] => 29
    [5] => 30
)
于 2012-11-12T21:05:26.437 回答