2009-12-13 30 views
0

如何讓數組增加到下一行?我正在製作一張寬3高10的標籤。我得到的結果是每行重複三次。我怎樣才能碰到每個表格單元格的下一行。遞增mysql_fetch_array?

$i =0; 
for ($i = 1; $i <= 3; ++$i){ 
while($row = mysql_fetch_array($result)){ 

$company = $row['company']; 
$comp_strt = $row['comp_strt']; 
$comp_city = $row['comp_city']; 
$comp_state = $row['comp_state']; 
$comp_zip = $row['comp_zip']; 
$celldata= $company."<br>".$comp_strt."<br>".$comp_city.",&nbsp;".$comp_state."&nbsp;".$comp_zip; 
if($i = 1){echo "<tr style='row-height: 5em;'><td>'".$celldata."'</td>";} 
if($i = 2){echo "<td>'".$celldata."'</td>";} 
if($i = 3){echo "<td>'".$celldata."'</td></tr>"; $i = 1;} 
}} 

回答

1

我這樣做:

$cellsPerRow = 3; 
$i = 0; 
echo '<table>'; 
while ($row = mysql_fetch_array($result)) { 
    if ($i % $cellsPerRow == 0) { 
     echo '<tr>'; 
    } 

    // process $row and echo the table cell 

    if ($i % $cellsPerRow == $cellsPerRow - 1) { 
     echo '</tr>'; 
    } 
    $i++; 
} 
if ($i > 0 && $i % $cellsPerRow != 0) { // finish off row if needed 
    while ($i % $cellsPerRow != 0) { 
     echo '<td></td>'; 
     $i++; 
    } 
    echo '</tr>'; 
} 
echo '</table>'; 

這將永遠給你一個適當的表。

+0

要花我一點時間(沒有雙關語意)來消化這一個。看來這個解決方案沒有留下任何可能的錯誤空間。謝謝Gumbo。 – Tom 2009-12-14 00:12:09

+0

@湯姆:那裏有一個。你應該測試是否有任何行。否則,你會得到打印的表格標籤,但沒有行/單元格。因此,在附加的* if語句的條件下使用'mysql_num_rows',這個語句包含整個'echo'

'; ... echo'
';'。 – Gumbo 2009-12-14 07:20:31

+0

是的,另一個if(!$ result)應該處理它。 – Tom 2009-12-15 14:51:31

0

如果你想畫彼此相鄰的3標籤,你只需要在合適的位置插入一個</tr><tr>塊。你只需有一個遞增的變量,無需對for循環:

$i = 0; 
echo '<table><tr>'; 
while($row = mysql_fetch_array($result)){ 
    if($i == 3) { 
     echo '</tr><tr>'; 
     $i = 0; 
    } 

    $company = $row['company']; 
    $comp_strt = $row['comp_strt']; 
    $comp_city = $row['comp_city']; 
    $comp_state = $row['comp_state']; 
    $comp_zip = $row['comp_zip']; 
    $celldata= $company."<br>".$comp_strt."<br>".$comp_city.",&nbsp;".$comp_state."&nbsp;".$comp_zip; 

    echo "<td>$celldata</td>"; 
    $i++; 
} 
echo '</tr></table>'; 

所以現在每次$i計數器達到3次,它會創建一個錶行突破,並設置$我回零,造成3每行的單元格。

-3

擺脫了對週期,如果你不想做三次,FFS使用=檢查平等

1

特殊照顧。你應該使用==

if($i == 1){echo "<tr style='row-height: 5em;'><td>'".$celldata."'</td>";} 
if($i == 2){echo "<td>'".$celldata."'</td>";} 
if($i == 3){echo "<td>'".$celldata."'</td></tr>"; $i = 1;} 

可能不會解決您的問題,但它是一個開始。

1

問題是while循環將不會退出,直到mysql_fetch_array中的行耗盡。只需使用while循環,增加$i內的while

$i= 0; 
while ($row = mysql_fetch_array($result)) { 
// process the row into $celldata 
if ($i==0 || $i%3==0) { 
    if ($i > 0) // close out existing row 
    // start a new row 
} 
// output cell data 
$i++; 
} 
// Output a closing '</tr>' tag if $i > 0 
+0

在該註釋中,強烈建議使用此處使用的模量運算符**%**,而不是重置計數器。 +1 – 2009-12-13 22:55:41