2010-03-18 126 views
1

我不知道這有多困難,但我有一個數組,並希望把它放到一個HTML表格。 我需要每行有兩個字符串數組,因此,如果是這樣的數組:從PHP陣列生成表格

$array1 = array(
    1 => 'one', 
    2 => 'two', 
    3 => 'three', 
    4 => 'four', 
    5 => "five", 
    6 => 'six', 
    ); 

我需要HTML表看起來像這樣:

| one | two | 
|three| four | 
|five | six | 

這是我的代碼:

$db = new Database(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE); 
$db->connect(); 

    $sql = "SELECT ID, movieno 
      FROM movies 
      ORDER BY ID DESC 
      LIMIT 6 "; 

    $rows = $db->query($sql); 

    print '<table width="307" border="0" cellspacing="5" cellpadding="4">'; 
    while ($record = $db->fetch_array($rows)) { 
     $vidaidi = $record['movieno']; 
     print <<<END 
     <tr> 
      <td> 
       <a href="http://www.youtube.com/watch?v=$vidaidi" target="_blank"> 

       <img src="http://img.youtube.com/vi/$vidaidi/1.jpg" width="123" height="80"></a> 
      </td> 
     </tr> 
    END; 
    } 
    print '</table>'; 

我想把它放在兩列。

+0

如果我打印甌$記錄我得到:資源ID#5,如果我打印$ vidaidi我得到陣列([ID] => 61 [movieno] => VpWnUkUdUA)嗯..我只收回陣列中的1行!如何提取1個數組中的所有數據? – robertdd 2010-03-18 07:08:49

回答

2

試試這個代碼...

<?php 

$array1 = array(
       1 => 'one', 
       2 => 'two', 
       3 => 'three', 
       4 => 'four', 
       5 => "five", 
       6 => 'six', 
       ); 

$val = current ($array1) ; 
print "<table border=1>"; 
while ($val) 
{ 
    print "<tr> <td> $val </td> "; 
    $val = next ($array1) ; 
    print "<td> $val </td> </tr> "; 
    print "\n"; 
    $val = next ($array1); 
} 

print "</table>"; 

?> 
2
$array1 = array(
    1 => 'one', 
    2 => 'two', 
    3 => 'three', 
    4 => 'four', 
    5 => "five", 
    6 => 'six', 
    ); 

echo '<table>'; 
for ($i = 1; $i <= 7; $i++) { 
    if ($i % 2 == 1) echo '<tr>'; 
    echo "<td>{$array1[$i]}</td>"; 
    if ($i % 2 == 2) echo '</tr>'; 
} 
echo '</table>'; 
0
echo "<table>"; 
for($i=0;$i+=2;$i<count($array1)) 
{ 
    echo "<tr><td>".$array1[$i]."</td><td>".isset($array1[$i+1])?$array1[$i+1]:'no value'."</td></tr>"; 
} 
echo "</table>" 
0

你可以這樣做:

print "<table>"; 
for($i=1;$i<=count($arr);$i++) { 
     if($i%2) 
       print"<tr><td>$arr[$i]</td>"; 
     else 
       print"<td>$arr[$i]</td></tr>\n"; 
} 
print "</table>";