2015-07-12 86 views
-1

這裏是MySQL表「成員」如何通過HTML表不同的行從MySQL數據庫組

Column1 
Jack 
Jack 
Jack 
Jack 
Mike 
Mike 
Mike 
John 
John 

我想要得到這樣的結果:

$row=mysql_query('SELECT * from members'); 
while ($row = mysql_fetch_array($row)) { 
echo" <table> 
     <tr> 
     <td>Jack</td> 
     <td>Jack</td> 
     <td>Jack</td> 
     <td>Jack</td> 
     </tr> 
     </table> 

     <table> 
     <tr> 
     <td>Mike</td> 
     <td>Mike</td> 
     <td>Mike</td> 
     </tr> 
     </table> 

     <table> 
     <tr> 
     <td>John</td> 
     <td>John</td> 
     </tr> 
     </table> "; } 

在每個HTML表必須只顯示類似的成員姓名。 在下表中必須顯示另一個類似的成員名稱。

+0

你的php代碼在哪裏? – Shehary

+0

如果我有php代碼,我不會在這裏問問題......! – user3391807

+0

有關使用'mysql_ *'函數的強制性註釋:雖然腳本中沒有任何動態查詢,但仍有許多原因需要使用(http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers#Why_use_PDO.3F) PDO或MySQLi覆蓋舊的和不推薦的'mysql_ *'函數。 – Tim

回答

1

下面是一個如何做到這一點的例子。它跟蹤以前的名稱,並將數據分配給數組,而前一個名稱與當前名稱匹配。當名稱與先前的名稱不匹配時,匹配數據數組將發送到輸出該表的函數。

我猜你會輸出更多的數據而不僅僅是名稱,所以如果是這樣的話,你可以通過在$ similarNames(array of array)中存儲一個數組來調整這段代碼只是名字。

<?php 

// get data and output in tables grouped by similar names 
function outputGroupedNames(){ 
    $previousName = ''; 
    $similarNames = array(); 
    $row=mysql_query('SELECT * from members'); 
    while ($row = mysql_fetch_array($row)) { 
     // if the current name matches the previous name, store the data 
     if($previousName == $row['name']){ 
      array_push($similarNames, $row['name']); 
     } 
     else { 
      // if the current name does not match the previous name, check if anything is stored in the data array (it will not be on the first item) and then call outputTable() 
      if(count($similarNames) > 0){ 
       outputTable($similarNames); 
       // 'reset' $similarNames with the current row data 
       $similarNames = array($row['name']); 
      } 
     } 
     $previousName = $row['name']; 
    } 
    // have to call this one more time at the end to output the last set of matches 
    outputTable($similarNames); 
} 

// takes an array of names and outputs them as an HTML table 
function outputTable($similarNames){ 
    echo '<table>'; 
    foreach($similarNames as $row){ 
     echo '<tr><td>' . $row . '</td></tr>'; 
    } 
    echo '</table>'; 
} 
相關問題