2012-11-12 113 views
0

假設您有一個30個字符的數組,並且循環它們以構建HTML中的可視化網格。我想知道它在最後一行的項目上,並應用CSS規則。對於每8個項目,我可以使用下面的代碼以進行額外的CSS規則:php循環 - 檢查總數之前的最後一個數字

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

因爲我只有30個字符,就會有3條線用較短的4號線(它只會有6項) 。我如何標記24-30中的每個字符屬於最後一行。字符的總數將始終變化。

+0

你是什麼意思摸索他們之後拿到最後一行標記每個字符24-30'..你還可以添加預期的結果嗎? – Baba

回答

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++; 
} 
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++; 
} 
+1

So $ cnt值永不改變。 :P – trickyzter

+0

@trickyzter哎呀。我只是複製並粘貼頂部的功能。我必須覆蓋$ cnt ++;很好的接收;) – Rooster

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"; 
} 
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 
) 
相關問題