Reputation: 39
Here is MYSQL table "Members"
Column1
Jack
Jack
Jack
Jack
Mike
Mike
Mike
John
John
I want get this result:
$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> "; }
In the every html table must be shown only similar members names. In the next table must be show another similar members names.
Upvotes: 0
Views: 692
Reputation: 6758
Below is an example of how you can do this. It keeps track of the previous name, and assigns the data to an array while the previous name matches the current name. When the name does not match the previous name, the array of matching data is sent to a function that outputs the table.
I'm guessing that you're going to be outputting more data than just the name, so if that's the case, you can adapt this code to your needs by storing an array in $similarNames (array of arrays) instead of just the name.
<?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>';
}
Upvotes: 1