Log in

View Full Version : Removing duplicate entries in while loop



hemi519
08-24-2012, 06:56 AM
Hi All,


In my program i am running a while loop which will produce one row for every loop, Now if you see the table user(9754) is there multiple times. Now i want to make sure that it is taking only the last row and leaving all the duplicate entries.






$query = mysql_query("select * from member where rank = '2'' ");
while($result = mysql_fetch_array($query))
{

$user = $result['code'];
$amount = $result['amount'];

echo "<tr><td> $user </td> <td> $amount </td> </tr>";

}



The above code will produce the following output inside a table




<table border="1" width="150" >
<tr> <td>
<td>User </td> <td>Amount</td></tr>
<td>3206</td> <td>606</td> </tr>
<td>9754</td> <td>60</td> </tr>
<td>9754</td> <td>70</td> </tr>
<td>9754</td> <td>140</td> </tr>
<td>9754</td> <td>240</td> </tr>
<td>2483</td> <td>350</td> </tr>
</table>



I want this to be like below





<table border="1" width="150" >
<tr> <td>
<td>User </td> <td>Amount</td></tr>
<td>3206</td> <td>606</td> </tr>
<td>9754</td> <td>240</td> </tr>
<td>2483</td> <td>350</td> </tr>
</table>



Can anyone help me how to solve this issue.

jscheuer1
08-24-2012, 01:15 PM
Pretty much the same way we did it in the other thread. Only instead of echoing from the while loop, use the loop to create the array, then echo from the processed array. Something like:


$query = mysql_query("select * from member where rank = '2'' ");
while($result = mysql_fetch_array($query)){
$temparray[] = $result['code'];
$temparray[] = $result['amount'];
}

foreach( $temparray as $key => $value ){
// use the % (modulus (remainder after division)) to determine if the key is odd or even
if( $key%2 === 0 ){
// it's even (or 0) --a customer number
$cust_no[$value] = isset($cust_no[$value])? $cust_no[$value] + $temparray[$key + 1] : $temparray[$key + 1];
}
}

// echo results:
foreach( $cust_no as $k => $v ){
echo "<tr><td> $k </td> <td> $v </td> </tr>";
}

Click SSL
09-04-2012, 06:10 AM
Hi,

Try this query...i think it's helpful

$query = mysql_query("select max(amount),code from member group by code where rank = '2'");