Jump to content

Testing for and hiding duplicate rows in array


garfee

Recommended Posts

Hi there.

 

I am trying to hide duplicate rows that are generated in my while loop.

 

My php is this:

<?php

// Start looping rows in mysql database.
$prev_category_name = false;
while($rows=mysql_fetch_array($result))
{
    $category_name = ($rows['category_id']);
    $items = ($rows['items']);
    $price = ($rows['price']);
        
        if ($category_name == $prev_category_name)
            {
                $category_name = '';
                    }
?>


<table>
<th><?php echo "$category_name"?></th>
<tr>
<td><?php echo "$items"?></td>
<td><?php echo "$price"?></td>
</tr>
</table>
<?php
$prev_category_name = $category_name;
}


?>

However. It only hides the duplicate if I have 2 or more items listed. For example, it would ouput this:

 

SHOES

Brown             £25.00

Red                £25.00

SHOES

Yellow             £25.00

 

When what I need it to output is this:

 

SHOES

Brown             £25.00

Red                £25.00

Yellow             £25.00

 

I am guessing it is doing this because the php is only testing the previous row for a duplicate, but I am not sure how to test all rows for a duplicate. Or even if this is the right thing to be doing.

 

Could anyone offer some advice and point me in the right direction.

 

Many thanks in advance.

 

ps. I am aware that DISTINCT in my SQL statement may solve the issue, but I want to be able to solve it using php.

You are creating a separate TABLE for each product. You need to move the TABLE tag to a place BEFORE the loop, and the closing TABLE tag to a place AFTER the loop.

 

The TH element needs to be INSIDE a table row

 

Your main problem is that you are setting $category to am empty string to stop it from printing. Then you assign $category to $prev_category_name to test the next iteration. Well, now the previous category is NOT equal to the next one. Do not change the category, as Barand showed, just output the heading inside the IF test if the current category does not match the previous one.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.