数组到一个表中,每行有5个单元格

时间:2012-02-01 16:37:55

标签: php html-table

如何将数组中的每个项目放入一个表格中,每行包含5个单元格或5列,并且不限制行数。

这是我的代码:

if (mysql_num_rows($badgedata) <= 0)
{
  $badge = "I have no badges =(";
}
else
{
  // Sets the array for the badges
  while($row = mysql_fetch_array($badgedata))
  {
    $badges[$row['badge_id']] = $row;
  }
  echo "<table><tbody>";
  // Displays the badges in the array
  foreach($badges as $badge => $id)
  {
    // I need the table here
    echo "<img src=\"http://habbome.com/r63/c_images/album1584/$badge.gif\" />";
  }
}

2 个答案:

答案 0 :(得分:1)

您需要在每个第五个单元格之前/之后回显<tr></tr>

$field = 0; // init field counter
echo "<table><tbody>";
// Displays the badges in the array
foreach($badges as $badge => $id)
{
    if ($field % 5 == 0) echo '<tr>'; // start line before field 0 .. 5 .. 10 etc.
    echo "<td><img src=\"http://habbome.com/r63/c_images/album1584/$badge.gif\" /></td>"; // output as table cell
    if ($field % 5 == 4) echo '</tr>'; // end line alter field 4 .. 9 .. 14 etc.
    $field++; // increase field counter
}
if ($field % 5 != 0) echo '</tr>'; // close last line, unless total count was multiple of 5
echo "</tbody></table>";

答案 1 :(得分:0)

为什么不尝试我的下一个方法

//For data Fetching
$strSQL = "select id,title from mytable";
$objResult = mysql_query($strSQL);
$arrResult = false;
while( $row = mysql_fetch_assoc( $objResult )){
    $arrResult[] = $row;
}

//in Template file or later use
if( !is_array($arrResult)){
   echo 'Sorry no result.';
}else{
    echo '<table>';
    foreach( $arrResult as $dataRow){
         echo '<tr>'.
               '<td>'.$dataRow['id'].'</td>'.
               '<td>'.$dataRow['title'].'</td>'.
               '</tr>';
    }
    echo '</table>';
}

通过这种方式,您可以构建多个记录/行和多列