2009-12-13 70 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