2017-02-16 50 views
2

我想用PHP創建一個動態表。行數將基於從mysql中提取的記錄數量,但我只希望一行中有4行。以下是我現在所擁有的動態表與PHP

$sql = "SELECT t.tankid,t.TankName,tc.paramid,tc.active,pr.paramname,pr.minvalue,pr.maxvalue,pr.incvalue,pr.value from mr_tanks t inner join mr_testconfig tc ON tc.tankid = t.tankid inner join mr_parameters pr ON tc.paramid = pr.parameterid where t.tankid = :tankid and t.active = 1 and tc.active = 1"; 
$records1 = $con->prepare($sql); 
$records1->bindParam(':tankid', $_GET['tankid']); 
$records1->execute(); 
$headers = $col = ""; 
while ($row1 = $records1->fetch(PDO::FETCH_ASSOC)) { 
    $headers .= "<th> {$row1['paramname']} </th>"; 
    $col .= "<td> {$row1['minvalue']} </td>"; 
} 
echo "<table><tr>$headers</tr><tr>$col</tr></table>"; 
?> 

什麼,我得到的是所有行均符合這樣的:

標題1個標題2標題3標題4標題5標題6標題7標題8
數據1數據2數據3數據4 數據5數據6數據7數據8

而且我想它是

標題1標題2標題3標題4
數據1數據2數據3數據4
頭5頭6頭7頭8
數據5數據6數據7數據8 孔

_____________________________________________________________ 
    | TestName 1 | TestName 2 | TestName 3 | TestName 4 | 
    |___________________________________________________________| 
    | ResultTest1 | ResultTest2 | ResultTest3 | ResultTest 4| 
    _____________________________________________________________ 
    | TestName 5 | TestName 6 | TestName 7 | TestName 8 | 
    |___________________________________________________________| 
    | ResultTest5 | ResultTest6 | ResultTest7 | ResultTest 8 |   

<table> 
    <tr> 
     <th> TestName 1</th> 
     <th> TestName 2</th> 
     <th> TestName 3</th> 
     <th> TestName 4</th> 
    </tr> 
    <tr> 
     <td> ResultTest 1</td> 
     <td> ResultTest 2</td> 
     <td> ResultTest 3</td> 
     <td> ResultTest 4</td> 
    </tr> 
    <tr> 
     <th> TestName 5</th> 
     <th> TestName 6</th> 
     <th> TestName 7</th> 
     <th> TestName 8</th> 
    </tr> 
    <tr> 
     <td> ResultTest 5</td> 
     <td> ResultTest 6</td> 
     <td> ResultTest 7</td> 
     <td> ResultTest 8</td> 
    </tr> 
</table>   
+1

這意味着兩張表,不是嗎? – JazZ

+0

你需要兩張桌子? –

+0

這是1桌子。在標題中是測試的名稱,數據中將是結果。 –

回答

0

您可以將行分塊爲2維數組,然後遍歷它們,其中每個塊將爲您提供一個單獨的表,每個表中有4行。

如果最後一個塊的行數少於4行,您可以決定讓表格少於4列,或者仍然需要它爲4列,然後使用空的參數名/ minvalue添加填充行。

$results = array(); 
while ($row1 = $records1->fetch(PDO::FETCH_ASSOC)) { 
    $results[] = $row1; 
} 

$results = array_chunk($results, 4); 
foreach($results as $chunk) { 
    $headers = ""; 
    $col = ""; 
    foreach($chunk as $row) { 
    $headers .= "<th> {$row)['paramname']} </th>"; 
    $col .= "<td> {$row)['minvalue']} </td>"; 
    } 
    echo "<table><tr>$headers</tr><tr>$col</tr></table>"; 
}