php循环 - 检查总数之前的最后一个数字

时间:2012-11-12 20:54:25

标签: php foreach

假设您有一个包含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 个答案:

答案 0 :(得分: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++;
}

答案 1 :(得分: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++;
}

答案 2 :(得分: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";
}

答案 3 :(得分: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
)