2010-05-20 30 views
1

我想在表格中顯示我的來自Mysql的查詢。然而,我的數據是這樣的:在表格中顯示PHP查詢數組

Array([0]=>data1, [1]=>data2, [2]=>data3,[3]=>data4,[4]=>pic1,[5]=>pic2,[6]=>pic3,[7]=>pic4); 

我要顯示我的表:

|data1 | data2 |data3 |data4 
|pic1 | pic2 |pic3 |pic4 

我知道如何顯示像TD或者tr,但不知道在單玲數據如何在同一個循環中執行tr和td。任何幫助?提前致謝!

while($query=mysql_fetch_array($dataQuery)){ 
//not sure what to do here. 
} 
+0

你能解釋更多關於如何知道如何將這個特定的例子分成兩行嗎?即爲什麼pic1和pic2在單獨的行上?僅僅是你只需要每行兩個元素,還是因爲某些元素是「數據」而其他元素是「圖片」? – 2010-05-20 14:11:36

+0

元素都是字符串。 Pic1只是一個例子。我想每行顯示至少3個數據。總共2排。該表將像上面更新的版本...謝謝 – FlyingCat 2010-05-20 14:17:18

+0

PerroVerd的答案似乎是最好的情況。您可以簡單地得到元素的總數,除以2,然後將$列設置爲該數字,從而產生兩行,無論結果的數量如何。 – 2010-05-20 14:32:43

回答

2

將兩行組裝成字符串,然後在表格行之間輸出它們可能更容易。你知道你有多少物品(行數),所以把它除以二。然後從這個數字中減去一個(你可能想要檢查它是否是你知道你沒有犯過錯誤)來說明事實上數組是從零開始的。遍歷整個數組。直到你到達中途點,你正在組裝你的標題行。之後,你正在組裝你的圖片行。然後在表格行標籤之間回顯結果。這裏有一個粗略的(未經測試的)代碼拍攝:

$rows = mysql_fetch_array($dataQuery); 
$total_rows = mysql_num_rows($rows); 
// check total_rows is even here? 
$midpoint = $total_rows/2 - 1; 
$title_row = ''; 
$photo_row = ''; 
foreach($rows as $num => $row) 
{ 
    $new_row = sprintf("\n\t<td>%s</td>", $row[0]); 
    if ($num < $midpoint) 
    { 
     $title_row .= $new_row; 
    } 
    else 
    { 
     $photo_row .= $new_row; 
    } 
} 

echo sprintf("\n<tr>%s</tr>", $title_row); 
echo sprintf("\n<tr>%s</tr>", $photo_row); 
+0

+1:這是我將如何解決它。 – Josh 2010-05-20 14:37:36

+0

謝謝你的幫助。 – FlyingCat 2010-05-20 15:08:11

+0

沒問題。我覺得我在其他例子中的代碼中存在一處錯誤),但很高興我能提供幫助。 – Tom 2010-05-20 16:25:55

2
<?php 
$rows = mysql_fetch_array($dataQuery); 
echo "<table><tr>"; 
foreach($rows as $num => $row){ 
    echo "<td>".$row[$num]."</td>"; // here we echo every object in array 
    if($num%2 == 0){ 
     echo "</tr><tr>"; // if we get to a number witch can be divided by 2 we add a new table row 
    } 
} 
echo "</tr></table>"; 
?>

我認爲這應該爲你工作。

+1

這不會產生'| data1 | data2'作爲第一行和'| data3 | data4'作爲第二個,'| pic1 |圖片2「作爲第三和」| pic3 |「 pic4'作爲第四行? – Josh 2010-05-20 14:23:58

+1

喬希。我更新了我的問題以顯示4列。原來的問題只有2列。 :D我正在研究他的解決方案。 – FlyingCat 2010-05-20 14:28:51

+0

它會正確地產生他第一次問他,現在他重拍了他的問題 – 2010-05-20 14:34:32

2

如果您有直線數據,但您知道應該使用計數器嘗試的列數。

$columns = 2; 
$ct = 0; 
while($query=mysql_fetch_array($dataQuery)) { 

    if ($ct % $columns == 0) echo "<tr>"; 

    echo '<td>' . query_data_to_extract . '</td>'; 
    $ct++; 

    if ($ct % $columns == 0) echo "</tr>"; 

} 
+0

PerroVerd。我不知道我會有多少列。它基於我的Mysql數據。您的解決方案適用於已知列。不過謝謝。 – FlyingCat 2010-05-20 14:37:21

+0

什麼是'query_data_to_extract'? – Josh 2010-05-20 14:45:53

+0

+1給你PerroVerd。謝謝。 – FlyingCat 2010-05-20 15:07:41