2015-07-12 92 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>'; 
} 
相关问题